code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
$(document).ready(function () {
$(".hide").click(function () {
$(this).closest(".expandedText").hide().prev(".show").show();
return false;
});
$(".show").click(function () {
$(this).hide().next(".expandedText").show();
return false;
});
$(".header").click(function () {
$header = $(this);
$content = $header.next();
$content.slideToggle(100, function() {
$header.text(function() {
return $content.is(":visible") ? "Design primers for known alleles (collapse)" : "Design primers for known alleles";
});
});
});
$(".header2").click(function () {
$header = $(this);
$content = $header.next();
$content.slideToggle(100, function() {
$header.text(function() {
return $content.is(":visible") ? "Design Screening Primers for Unknown CRISPR Editing (collapse)" : "Design Screening Primers for Unknown CRISPR Editing";
});
});
});
});
| KieberLab/indCAPS | static/index.js | JavaScript | bsd-3-clause | 878 |
/* Set the defaults for DataTables initialisation */
$.extend(true, $.fn.dataTable.defaults, {
"sDom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>" + "t" + "<'row'<'col-sm-6'i><'col-sm-6'p>>",
"oLanguage": {
"sLengthMenu": "_MENU_ Registros por página"
}
});
/* Default class modification */
$.extend($.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline",
"sFilterInput": "form-control input-sm",
"sLengthSelect": "form-control input-sm"
});
// In 1.10 we use the pagination renderers to draw the Bootstrap paging,
// rather than custom plug-in
if ($.fn.dataTable.Api) {
$.fn.dataTable.defaults.renderer = 'bootstrap';
$.fn.dataTable.ext.renderer.pageButton.bootstrap = function(settings, host, idx, buttons, page, pages) {
var api = new $.fn.dataTable.Api(settings);
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass;
var attach = function(container, buttons) {
var i, ien, node, button;
var clickHandler = function(e) {
e.preventDefault();
if (e.data.action !== 'ellipsis') {
api.page(e.data.action).draw(false);
}
};
for (i = 0, ien = buttons.length; i < ien; i++) {
button = buttons[i];
if ($.isArray(button)) {
attach(container, button);
} else {
btnDisplay = '';
btnClass = '';
switch (button) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages - 1 ?
'' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages - 1 ?
'' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if (btnDisplay) {
node = $('<li>', {
'class': classes.sPageButton + ' ' + btnClass,
'aria-controls': settings.sTableId,
'tabindex': settings.iTabIndex,
'id': idx === 0 && typeof button === 'string' ? settings.sTableId + '_' + button : null
})
.append($('<a>', {
'href': '#'
})
.html(btnDisplay)
)
.appendTo(container);
settings.oApi._fnBindAction(
node, {
action: button
}, clickHandler
);
}
}
}
};
attach(
$(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
}
} else {
// Integration for 1.9-
$.fn.dataTable.defaults.sPaginationType = 'bootstrap';
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function(oSettings) {
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
"iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
};
};
/* Bootstrap style pagination control */
$.extend($.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function(oSettings, nPaging, fnDraw) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function(e) {
e.preventDefault();
if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
fnDraw(oSettings);
}
};
$(nPaging).append(
'<ul class="pagination">' +
'<li class="prev disabled"><a href="#">← ' + oLang.sPrevious + '</a></li>' +
'<li class="next disabled"><a href="#">' + oLang.sNext + ' → </a></li>' +
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind('click.DT', {
action: "previous"
}, fnClickHandler);
$(els[1]).bind('click.DT', {
action: "next"
}, fnClickHandler);
},
"fnUpdate": function(oSettings, fnDraw) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, ien, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2);
if (oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
} else if (oPaging.iPage <= iHalf) {
iStart = 1;
iEnd = iListLength;
} else if (oPaging.iPage >= (oPaging.iTotalPages - iHalf)) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for (i = 0, ien = an.length; i < ien; i++) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for (j = iStart; j <= iEnd; j++) {
sClass = (j == oPaging.iPage + 1) ? 'class="active"' : '';
$('<li ' + sClass + '><a href="#">' + j + '</a></li>')
.insertBefore($('li:last', an[i])[0])
.bind('click', function(e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(), 10) - 1) * oPaging.iLength;
fnDraw(oSettings);
});
}
// Add / remove disabled classes from the static elements
if (oPaging.iPage === 0) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
});
}
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ($.fn.DataTable.TableTools) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend(true, $.fn.DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info modal"
},
"select": {
"row": "active"
}
});
// Have the collection use a bootstrap compatible dropdown
$.extend(true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
});
}
| victorpenia/systemAC | public/js/plugins/dataTables/dataTables.bootstrap.js | JavaScript | bsd-3-clause | 9,619 |
import { Map } from 'immutable';
import {
BLACK,
SIZE_3,
DRAW
} from './markerConstants';
export const initialMarker = Map({
color: BLACK,
size: SIZE_3,
mode: DRAW
});
import {
CHANGE_COLOR,
CHANGE_SIZE,
CHANGE_MODE
} from './../../src/client/app/toolbar/toolbarActions';
const markerReducer = (state = initialMarker, action) => {
switch (action.type) {
case CHANGE_COLOR:
return state.set('color', action.color);
case CHANGE_SIZE:
return state.set('size', action.size);
case CHANGE_MODE:
return state.set('mode', action.mode);
default:
return state;
}
};
export default markerReducer;
| jackrzhang/boardsession | src/state/markerReducer.js | JavaScript | bsd-3-clause | 653 |
"use strict";
var db = require('../../models');
var generate = require('../../lib/generate');
var assertions = require('../assertions');
var requestHelper = require('../request-helper');
var dbHelper = require('../db-helper');
/*
* For testing, create three clients:
*
* - a device in user mode (101) that has access token for domain
* example-service.bbc.co.uk (201)
* - a device in client mode (102) that has access token for domain
* example-service.com (202)
* - a web server (103) that has access token for domain
* example-service.bbc.co.uk (201)
*/
var initDatabase = function(done) {
db.Client
.create({
id: 101,
secret: 'e2412cd1-f010-4514-acab-c8af59e5501a',
name: 'User mode test client',
software_id: 'CPA AP Test',
software_version: '0.0.1',
ip: '127.0.0.1',
registration_type: 'dynamic',
user_id: 301,
})
.then(function() {
return db.Client.create({
id: 102,
secret: '751ae023-7dc0-4650-b0ff-e48ea627d6b2',
name: 'Client mode test client',
software_id: 'CPA AP Test',
software_version: '0.0.1',
ip: '127.0.0.1',
registration_type: 'dynamic',
user_id: null
});
})
.then(function() {
return db.Client.create({
id: 103,
secret: '399a8f42-365e-42db-a745-cf8b0e5b7ab7',
name: 'Webserver test client',
software_id: 'CPA AP Test',
software_version: '0.0.1',
ip: '127.0.0.1',
registration_type: 'static',
redirect_uri: 'https://example-client.com/cpa/callback',
user_id: null
});
})
.then(function() {
return db.Domain.create({
id: 201,
name: 'example-service.bbc.co.uk',
display_name: 'BBC Radio',
access_token: '70fc2cbe54a749c38da34b6a02e8dfbd'
});
})
.then(function() {
return db.Domain.create({
id: 202,
name: 'example-service.com',
display_name: 'CPA Example Service',
access_token: '44e948140678443fbe1d89d1b7313911'
});
})
.then(function() {
return db.User.create({
id: 301,
provider_uid: 'testuser',
display_name: 'Test User',
password: 'testpassword'
});
})
.then(function() {
return db.User.create({
id: 302,
provider_uid: 'anothertestuser',
display_name: 'Another Test User',
password: 'testpassword'
});
})
.then(function() {
// Access token for device client in user mode
return db.AccessToken.create({
token: '2d18047c-a07b-4a84-a81c-ad2bf23a8753',
client_id: 101,
user_id: 301,
domain_id: 201
});
})
.then(function() {
// Access token for device client in client mode
return db.AccessToken.create({
token: 'b3248f78-7ffd-466a-ba2b-50a6616aefb9',
client_id: 102,
user_id: null,
domain_id: 202
});
})
.then(function() {
// Access token for web server client
return db.AccessToken.create({
token: '9d009168-c841-4ecd-abf6-0278722fac05',
client_id: 103,
user_id: 302,
domain_id: 201
});
})
.then(function() {
done();
},
function(error) {
done(new Error(JSON.stringify(error)));
});
};
var resetDatabase = function(done) {
return dbHelper.resetDatabase(initDatabase, done);
};
describe("POST /token", function() {
before(function() {
sinon.stub(generate, 'accessToken').returns('aed201ffb3362de42700a293bdebf694');
});
after(function() {
generate.accessToken.restore();
});
context("Refreshing an access token", function() {
context("with a device client", function() {
context("that has an existing user mode access token for the requested domain", function() {
before(function() {
var time = new Date("Wed Apr 09 2014 11:00:00 GMT+0100").getTime();
this.clock = sinon.useFakeTimers(time, "Date");
});
after(function() {
this.clock.restore();
});
before(resetDatabase);
before(function(done) {
var requestBody = {
grant_type: 'http://tech.ebu.ch/cpa/1.0/client_credentials',
client_id: '101',
client_secret: 'e2412cd1-f010-4514-acab-c8af59e5501a',
domain: 'example-service.bbc.co.uk'
};
requestHelper.sendRequest(this, '/token', {
method: 'post',
type: 'json',
data: requestBody
}, done);
});
it("should return status 200", function() {
expect(this.res.statusCode).to.equal(200);
});
it("should return a Cache-Control: no-store header", function() {
expect(this.res.headers).to.have.property('cache-control');
expect(this.res.headers['cache-control']).to.equal('no-store');
});
it("should return a Pragma: no-cache header", function() {
expect(this.res.headers).to.have.property('pragma');
expect(this.res.headers.pragma).to.equal('no-cache');
});
it("should return a JSON object", function() {
expect(this.res.headers['content-type']).to.equal('application/json; charset=utf-8');
expect(this.res.body).to.be.an('object');
});
describe("the response body", function() {
it("should include the user name", function() {
expect(this.res.body).to.have.property('user_name');
expect(this.res.body.user_name).to.equal('Test User');
});
it("should include a valid access token", function() {
expect(this.res.body).to.have.property('access_token');
expect(this.res.body.access_token).to.equal('aed201ffb3362de42700a293bdebf694');
});
it("should include the token type", function() {
expect(this.res.body).to.have.property('token_type');
expect(this.res.body.token_type).to.equal('bearer');
});
it("should include the domain", function() {
expect(this.res.body).to.have.property('domain');
expect(this.res.body.domain).to.equal('example-service.bbc.co.uk');
});
it("should include a display name for the domain", function() {
expect(this.res.body).to.have.property('domain_display_name');
expect(this.res.body.domain_display_name).to.equal('BBC Radio');
});
it("should include the lifetime of the access token", function() {
expect(this.res.body).to.have.property('expires_in');
expect(this.res.body.expires_in).to.equal(30 * 24 * 60 * 60);
});
it("should include the scope of the access token"); // TODO: optional(?): scope
});
describe("the database", function() {
before(function(done) {
var self = this;
db.AccessToken.findAll({ where: { client_id: 101 } })
.then(function(accessTokens) {
self.accessTokens = accessTokens;
done();
},
function(error) {
done(error);
});
});
it("should contain the new access token", function() {
expect(this.accessTokens.length).to.equal(1);
});
describe("the access token", function() {
it("should have correct value", function() {
expect(this.accessTokens[0].token).to.equal('aed201ffb3362de42700a293bdebf694');
});
it("should be associated with the correct client", function() {
expect(this.accessTokens[0].client_id).to.equal(101);
});
it("should be associated with the correct user", function() {
expect(this.accessTokens[0].user_id).to.equal(301);
});
it("should be associated with the correct domain", function() {
expect(this.accessTokens[0].domain_id).to.equal(201);
});
});
});
});
context("that has an existing client mode access token for the requested domain", function() {
before(function() {
var time = new Date("Wed Apr 09 2014 11:00:00 GMT+0100").getTime();
this.clock = sinon.useFakeTimers(time, "Date");
});
after(function() {
this.clock.restore();
});
before(resetDatabase);
before(function(done) {
var requestBody = {
grant_type: 'http://tech.ebu.ch/cpa/1.0/client_credentials',
client_id: '102',
client_secret: '751ae023-7dc0-4650-b0ff-e48ea627d6b2',
domain: 'example-service.com'
};
requestHelper.sendRequest(this, '/token', {
method: 'post',
type: 'json',
data: requestBody
}, done);
});
it("should return status 200", function() {
expect(this.res.statusCode).to.equal(200);
});
it("should return a Cache-Control: no-store header", function() {
expect(this.res.headers).to.have.property('cache-control');
expect(this.res.headers['cache-control']).to.equal('no-store');
});
it("should return a Pragma: no-cache header", function() {
expect(this.res.headers).to.have.property('pragma');
expect(this.res.headers.pragma).to.equal('no-cache');
});
it("should return a JSON object", function() {
expect(this.res.headers['content-type']).to.equal('application/json; charset=utf-8');
expect(this.res.body).to.be.an('object');
});
describe("the response body", function() {
it("should not include a the user name", function() {
expect(this.res.body).to.not.have.property('user_name');
});
it("should include a valid access token", function() {
expect(this.res.body).to.have.property('access_token');
expect(this.res.body.access_token).to.equal('aed201ffb3362de42700a293bdebf694');
});
it("should include the token type", function() {
expect(this.res.body).to.have.property('token_type');
expect(this.res.body.token_type).to.equal('bearer');
});
it("should include the domain", function() {
expect(this.res.body).to.have.property('domain');
expect(this.res.body.domain).to.equal('example-service.com');
});
it("should include a display name for the domain", function() {
expect(this.res.body).to.have.property('domain_display_name');
expect(this.res.body.domain_display_name).to.equal('CPA Example Service');
});
it("should include the lifetime of the access token", function() {
expect(this.res.body).to.have.property('expires_in');
expect(this.res.body.expires_in).to.equal(30 * 24 * 60 * 60);
});
it("should include the scope of the access token"); // TODO: optional(?): scope
});
describe("the database", function() {
before(function(done) {
var self = this;
db.AccessToken.findAll({ where: { client_id: 102 } })
.then(function(accessTokens) {
self.accessTokens = accessTokens;
return db.Client.find(102);
})
.then(function(client) {
self.client = client;
done();
},
function(error) {
done(error);
});
});
it("should contain the new access token", function() {
expect(this.accessTokens.length).to.equal(1);
});
describe("the access token", function() {
it("should have correct value", function() {
expect(this.accessTokens[0].token).to.equal('aed201ffb3362de42700a293bdebf694');
});
it("should be associated with the correct client", function() {
expect(this.accessTokens[0].client_id).to.equal(102);
});
it("should not be associated a user", function() {
expect(this.accessTokens[0].user_id).to.equal(null);
});
it("should be associated with the correct domain", function() {
expect(this.accessTokens[0].domain_id).to.equal(202);
});
});
describe("the client", function() {
it("should not be associated with a user", function() {
expect(this.client.user_id).to.equal(null);
});
});
});
});
context("with an unknown client", function() {
before(resetDatabase);
before(function(done) {
var requestBody = {
grant_type: 'http://tech.ebu.ch/cpa/1.0/client_credentials',
client_id: 'unknown',
client_secret: 'unknown',
domain: 'example-service.bbc.co.uk'
};
requestHelper.sendRequest(this, '/token', {
method: 'post',
type: 'json',
data: requestBody
}, done);
});
it("should return an invalid_client error", function() {
assertions.verifyError(this.res, 400, 'invalid_client');
});
});
});
context("with a web server client", function() {
before(resetDatabase);
before(function(done) {
var requestBody = {
grant_type: 'http://tech.ebu.ch/cpa/1.0/client_credentials',
client_id: '103',
client_secret: '399a8f42-365e-42db-a745-cf8b0e5b7ab7',
domain: 'example-service.bbc.co.uk'
};
requestHelper.sendRequest(this, '/token', {
method: 'post',
type: 'json',
data: requestBody
}, done);
});
it("should return an invalid_client error", function() {
assertions.verifyError(this.res, 400, 'invalid_client');
});
});
});
var fields = ['client_id', 'client_secret', 'domain'];
fields.forEach(function(field) {
context('with missing ' + field + ' field', function() {
before(resetDatabase);
before(function(done) {
var data = {
grant_type: 'http://tech.ebu.ch/cpa/1.0/client_credentials',
client_id: '101',
client_secret: 'e2412cd1-f010-4514-acab-c8af59e5501a',
domain: 'example-service.bbc.co.uk'
};
delete data[field];
requestHelper.sendRequest(this, '/token', {
method: 'post',
type: 'json',
data: data,
}, done);
});
it("should return an invalid_request error", function() {
assertions.verifyError(this.res, 400, 'invalid_request');
});
});
});
context("with an extra field in the request body", function() {
before(resetDatabase);
before(function(done) {
var data = {
grant_type: 'http://tech.ebu.ch/cpa/1.0/client_credentials',
client_id: '101',
client_secret: 'e2412cd1-f010-4514-acab-c8af59e5501a',
domain: 'example-service.bbc.co.uk',
extra: 'test'
};
requestHelper.sendRequest(this, '/token', {
method: 'post',
type: 'json',
data: data,
}, done);
});
it("should return an invalid_request error", function() {
assertions.verifyError(this.res, 400, 'invalid_request');
});
});
});
| ebu/cpa-auth-provider | test/lib/refresh-device-token.js | JavaScript | bsd-3-clause | 16,086 |
var greyout = function(opts){
if(this === window) return false;
if(opts !== undefined && typeof opts !== 'object') return false;
var _grey = {};
_grey.find = ((typeof opts === 'undefined') ? true : ((typeof opts.hierarchy === 'undefined') ? true : false ));
_grey.action = ((typeof opts !== 'undefined') ? ((typeof opts.action === 'undefined') ? 'disable' : opts.action ) : 'disable');
_grey.placeholder = ((typeof opts !== 'undefined') ? ((typeof opts.placeholder === 'undefined') ? null : opts.placeholder ) : null);
_grey.contro_class = ((typeof opts !== 'undefined') ? ((typeof opts.controller_class === 'undefined') ? null : opts.controller_class ) : null);
_grey.condi_class = ((typeof opts !== 'undefined') ? ((typeof opts.conditional_class === 'undefined') ? null : opts.conditional_class ) : null);
_grey.rem_condi = ((typeof opts !== 'undefined') ? ((typeof opts.remove_conditional_class === 'undefined') ? true : false ) : true);
_grey.dis_class = ((typeof opts !== 'undefined') ? ((typeof opts.disabled_class === 'undefined') ? null : opts.disabled_class ) : null);
_grey.logging = ((typeof opts !== 'undefined') ? ((typeof opts.logging === 'undefined') ? 0 : ((typeof opts.logging === 'number' && opts.logging >= 0) ? opts.logging : 0) ) : 0);
_grey.logger = function(){
if(typeof console === 'undefined' || typeof console.log === 'undefined') return false;
if(arguments.length < 1) return false;
arguments = Array.prototype.slice.call(arguments);
if(arguments.length < 2) arguments.push(1);
if(arguments.pop() <= _grey.logging){
console.log.apply(console, arguments);
if(typeof console.trace !== 'undefined'){
console.trace();
}
}
};
_grey.parseAttribs = function(elem){
_grey.elems = _grey.elems || {};
elem = ((typeof elem === 'object') ? jQuery(elem) : jQuery('#'+elem));
_contr = ((typeof elem.data('greyout-controllers') === 'undefined') ? false : elem.data('greyout-controllers').split(','));
if(!_contr) return false;
for(i = 0, l = _contr.length; i < l; i++){
_el = ((typeof jQuery("#"+_contr[i])[0] === 'undefined') ? false : jQuery("#"+_contr[i]));
if(_el){
if(typeof _grey.elems[elem[0].id] === 'undefined'){
_grey.elems[elem[0].id] = {name: elem[0].id, controllers: [_contr[i]]};
} else {
_grey.elems[elem[0].id].controllers.push(_contr[i]);
}
}
}
};
_grey.keyup = function(e){
_elem = ((typeof e.target === 'undefined') ? e : "#"+e.target.id);
_elem = jQuery(_elem);
for(el in _grey.elems){
_contr = _grey.elems[el].controllers;
if(_contr.indexOf(_elem[0].id) >= 0){
if(_elem.val().length > 0){
_grey.hider(_grey.elems[el].name);
} else {
_grey.shower(_grey.elems[el].name);
}
}
}
};
_grey.hider = function(elem){
elem = '#'+elem;
if(jQuery(elem).val().length > 0){
jQuery(elem).attr('data-greyout-oldval', jQuery(elem).val());
jQuery(elem).val(null);
_grey.keyup(elem);
}
switch(_grey.action){
case 'hide':
if(jQuery.hide){
jQuery(elem).hide();
}
case 'disable':
default:
jQuery(elem).attr('placeholder', _grey.placeholder);
jQuery(elem).attr('disabled', 'disabled');
if(_grey.dis_class !== false){
jQuery(elem).addClass(((_grey.dis_class !== null) ? _grey.dis_class : "greyout-disabled"));
}
break;
}
};
_grey.shower = function(elem){
_contr = _grey.elems[elem].controllers;
for(i = 0, l = _contr.length; i < l; i++){
if(jQuery('#'+_contr[i]).val().length > 0) return false;
}
elem = '#'+elem;
jQuery(elem).attr('placeholder', null);
if(typeof jQuery(elem).attr('data-greyout-oldval') !== 'undefined'){
jQuery(elem).val(jQuery(elem).attr('data-greyout-oldval'));
jQuery(elem).removeAttr('data-greyout-oldval');
_grey.keyup(elem);
}
switch(_grey.action){
case 'hide':
if(jQuery.show){
jQuery(elem).show();
}
case 'disable':
default:
jQuery(elem).removeAttr('disabled');
jQuery(elem).removeClass("greyout-disabled "+_grey.dis_class);
break;
}
};
/* populate _grey.elems with an element relationship map */
if(_grey.find){
jQuery.each(jQuery('input'), function(i, v){
_grey.parseAttribs(v);
});
} else {
_grey.elems = opts.hierarchy;
}
/* attempt to apply conditional and controller classes */
if(_grey.condi_class !== false){
jQuery.each(_grey.elems, function(i, v){
jQuery('#'+v.name).addClass(function(i, c){
if(c.indexOf(_grey.condi_class) < 0){
return ((_grey.condi_class !== null) ? _grey.condi_class : "greyout-conditional");
}
});
});
}
if(_grey.contro_class !== false){
jQuery.each(_grey.elems, function(i, v){
jQuery.each(v.controllers, function(i, c){
if(_grey.rem_condi){
jQuery('#'+c).removeClass("greyout-conditional "+_grey.condi_class);
}
jQuery('#'+c).addClass(function(i, _c){
if(_c.indexOf(_grey.contro_class) < 0){
return ((_grey.contro_class !== null) ? _grey.contro_class : "greyout-controller");
}
});
});
});
}
/* apply keyup event listeners to controllers */
for(el in _grey.elems){
if(typeof _grey.elems[el] !== 'undefined'){
_contr = _grey.elems[el].controllers;
for(_elem in _contr){
jQuery('#'+_contr[_elem]).on('keyup', _grey.keyup);
}
}
}
/* return object */
this._grey = _grey;
return this;
}
if(typeof jQuery !== 'undefined'){
(function($){
$.greyout = greyout;
greyout = null;
})(jQuery);
} | Ultrabenosaurus/greyout.js | greyout.js | JavaScript | bsd-3-clause | 5,434 |
/*\
title: $:/core/modules/utils/dom.js
type: application/javascript
module-type: utils
Various static DOM-related utility functions.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Determines whether element 'a' contains element 'b'
Code thanks to John Resig, http://ejohn.org/blog/comparing-document-position/
*/
exports.domContains = function(a,b) {
return a.contains ?
a !== b && a.contains(b) :
!!(a.compareDocumentPosition(b) & 16);
};
exports.removeChildren = function(node) {
while(node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
};
exports.hasClass = function(el,className) {
return el && el.className && el.className.split(" ").indexOf(className) !== -1;
};
exports.addClass = function(el,className) {
var c = el.className.split(" ");
if(c.indexOf(className) === -1) {
c.push(className);
}
el.className = c.join(" ");
};
exports.removeClass = function(el,className) {
var c = el.className.split(" "),
p = c.indexOf(className);
if(p !== -1) {
c.splice(p,1);
el.className = c.join(" ");
}
};
exports.toggleClass = function(el,className,status) {
if(status === undefined) {
status = !exports.hasClass(el,className);
}
if(status) {
exports.addClass(el,className);
} else {
exports.removeClass(el,className);
}
};
/*
Get the scroll position of the viewport
Returns:
{
x: horizontal scroll position in pixels,
y: vertical scroll position in pixels
}
*/
exports.getScrollPosition = function() {
if("scrollX" in window) {
return {x: window.scrollX, y: window.scrollY};
} else {
return {x: document.documentElement.scrollLeft, y: document.documentElement.scrollTop};
}
};
/*
Gets the bounding rectangle of an element in absolute page coordinates
*/
exports.getBoundingPageRect = function(element) {
var scrollPos = $tw.utils.getScrollPosition(),
clientRect = element.getBoundingClientRect();
return {
left: clientRect.left + scrollPos.x,
width: clientRect.width,
right: clientRect.right + scrollPos.x,
top: clientRect.top + scrollPos.y,
height: clientRect.height,
bottom: clientRect.bottom + scrollPos.y
};
};
/*
Saves a named password in the browser
*/
exports.savePassword = function(name,password) {
if(window.localStorage) {
localStorage.setItem("tw5-password-" + name,password);
}
};
/*
Retrieve a named password from the browser
*/
exports.getPassword = function(name) {
return window.localStorage ? localStorage.getItem("tw5-password-" + name) : "";
};
/*
Force layout of a dom node and its descendents
*/
exports.forceLayout = function(element) {
var dummy = element.offsetWidth;
};
/*
Pulse an element for debugging purposes
*/
exports.pulseElement = function(element) {
// Event handler to remove the class at the end
element.addEventListener($tw.browser.animationEnd,function handler(event) {
element.removeEventListener($tw.browser.animationEnd,handler,false);
$tw.utils.removeClass(element,"pulse");
},false);
// Apply the pulse class
$tw.utils.removeClass(element,"pulse");
$tw.utils.forceLayout(element);
$tw.utils.addClass(element,"pulse");
};
/*
Attach specified event handlers to a DOM node
domNode: where to attach the event handlers
events: array of event handlers to be added (see below)
Each entry in the events array is an object with these properties:
handlerFunction: optional event handler function
handlerObject: optional event handler object
handlerMethod: optionally specifies object handler method name (defaults to `handleEvent`)
*/
exports.addEventListeners = function(domNode,events) {
$tw.utils.each(events,function(eventInfo) {
var handler;
if(eventInfo.handlerFunction) {
handler = eventInfo.handlerFunction;
} else if(eventInfo.handlerObject) {
if(eventInfo.handlerMethod) {
handler = function(event) {
eventInfo.handlerObject[eventInfo.handlerMethod].call(eventInfo.handlerObject,event);
};
} else {
handler = eventInfo.handlerObject;
}
}
domNode.addEventListener(eventInfo.name,handler,false);
});
};
})();
| TeravoxelTwoPhotonTomography/nd | doc/node_modules/tiddlywiki/core/modules/utils/dom/dom.js | JavaScript | bsd-3-clause | 4,050 |
describe 'Concrete'
describe 'Super'
before
$('body').append('<div id="dom_test"></div>')
end
after
$('#dom_test').remove()
end
before_each
$.concrete.clear_all_rules()
$('#dom_test').html('<div id="a" class="a b c">Foo</div><div id="b" class="c d e">Bar</div>')
end
it 'can call the super function'
var a = 1;
$('#a').concrete({
foo: function(){a *= 2;}
});
$('#a.a').concrete({
foo: function(){a += 2; this._super();}
});
$('#a').foo();
a.should.equal 6
end
it 'super to a non-existant class should be ignored'
var a = 1;
$('#a').concrete({
foo: function(){a *= 2; this._super();}
});
$('#a.a').concrete({
foo: function(){a += 2; this._super();}
});
$('#a').foo();
a.should.equal 6
end
it 'can call super from two different functions without screwing up what super points to'
var list = [];
$('#a').concrete({
foo: function(){ list.push('foo'); this.bar(); },
bar: function(){ list.push('bar'); }
});
$('#a.a').concrete({
foo: function(){ list.push('foo2'); this._super(); list.push('foo2'); this._super(); },
bar: function(){ list.push('bar2'); this._super(); }
});
$('#a').foo();
list.should.eql [ 'foo2', 'foo', 'bar2', 'bar', 'foo2', 'foo', 'bar2', 'bar' ]
end
it 'can override (and call via super) a non-concrete jquery function'
var a = 1
$('#a').concrete({
text: function(){ a = this._super(); }
});
$('#a').text();
a.should.equal 'Foo'
$('#b').text().should.equal 'Bar'
end
end
end
| hafriedlander/jquery.concrete | spec/legacy/spec.concrete.super.js | JavaScript | bsd-3-clause | 1,744 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'settings-certificate-manager-page' is the settings page
* containing SSL certificate settings.
*/
Polymer({
is: 'settings-certificate-manager-page',
behaviors: [WebUIListenerBehavior],
properties: {
/** @type {number} */
selected: {
type: Number,
value: 0,
},
/** @type {!Array<!Certificate>} */
personalCerts: {
type: Array,
value: function() { return []; },
},
/** @type {!Array<!Certificate>} */
serverCerts: {
type: Array,
value: function() { return []; },
},
/** @type {!Array<!Certificate>} */
caCerts: {
type: Array,
value: function() { return []; },
},
/** @type {!Array<!Certificate>} */
otherCerts: {
type: Array,
value: function() { return []; },
},
/** @private */
certificateTypeEnum_: {
type: Object,
value: settings.CertificateType,
readonly: true,
},
/** @private */
showCaTrustEditDialog_: Boolean,
/** @private */
showDeleteConfirmationDialog_: Boolean,
/** @private */
showPasswordEncryptionDialog_: Boolean,
/** @private */
showPasswordDecryptionDialog_: Boolean,
/** @private */
showErrorDialog_: Boolean,
/**
* The model to be passed to dialogs that refer to a given certificate.
* @private {?CertificateSubnode}
*/
dialogModel_: Object,
/**
* The certificate type to be passed to dialogs that refer to a given
* certificate.
* @private {?settings.CertificateType}
*/
dialogModelCertificateType_: String,
/**
* The model to be passed to the error dialog.
* @private {null|!CertificatesError|!CertificatesImportError}
*/
errorDialogModel_: Object,
},
/** @override */
attached: function() {
this.addWebUIListener('certificates-changed', this.set.bind(this));
settings.CertificatesBrowserProxyImpl.getInstance().refreshCertificates();
},
/**
* @param {number} selectedIndex
* @param {number} tabIndex
* @return {boolean} Whether to show tab at |tabIndex|.
* @private
*/
isTabSelected_: function(selectedIndex, tabIndex) {
return selectedIndex == tabIndex;
},
/** @override */
ready: function() {
this.addEventListener(settings.CertificateActionEvent, function(event) {
this.dialogModel_ = event.detail.subnode;
this.dialogModelCertificateType_ = event.detail.certificateType;
if (event.detail.action == settings.CertificateAction.IMPORT) {
if (event.detail.certificateType == settings.CertificateType.PERSONAL) {
this.openDialog_(
'settings-certificate-password-decryption-dialog',
'showPasswordDecryptionDialog_');
} else if (event.detail.certificateType ==
settings.CertificateType.CA) {
this.openDialog_(
'settings-ca-trust-edit-dialog', 'showCaTrustEditDialog_');
}
} else {
if (event.detail.action == settings.CertificateAction.EDIT) {
this.openDialog_(
'settings-ca-trust-edit-dialog', 'showCaTrustEditDialog_');
} else if (event.detail.action == settings.CertificateAction.DELETE) {
this.openDialog_(
'settings-certificate-delete-confirmation-dialog',
'showDeleteConfirmationDialog_');
} else if (event.detail.action ==
settings.CertificateAction.EXPORT_PERSONAL) {
this.openDialog_(
'settings-certificate-password-encryption-dialog',
'showPasswordEncryptionDialog_');
}
}
event.stopPropagation();
}.bind(this));
this.addEventListener('certificates-error', function(event) {
this.errorDialogModel_ = event.detail;
this.openDialog_(
'settings-certificates-error-dialog',
'showErrorDialog_');
event.stopPropagation();
}.bind(this));
},
/**
* Opens a dialog and registers a listener for removing the dialog from the
* DOM once is closed. The listener is destroyed when the dialog is removed
* (because of 'restamp').
*
* @param {string} dialogTagName The tag name of the dialog to be shown.
* @param {string} domIfBooleanName The name of the boolean variable
* corresponding to the dialog.
* @private
*/
openDialog_: function(dialogTagName, domIfBooleanName) {
this.set(domIfBooleanName, true);
this.async(function() {
var dialog = this.$$(dialogTagName);
dialog.addEventListener('iron-overlay-closed', function() {
this.set(domIfBooleanName, false);
}.bind(this));
}.bind(this));
},
});
| was4444/chromium.src | chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js | JavaScript | bsd-3-clause | 4,848 |
import {concat} from "ramda"
import mergeWith from "@unction/mergewith"
import isObject from "@unction/isobject"
import isArray from "@unction/isarray"
export default function mergeDeepLeft (left: IterableType): Function {
return function mergeDeepLeftLeft (right: IterableType): IterableType {
if (isArray(left) && isArray(right)) {
return concat(left)(right)
}
if (isObject(left) && isObject(right)) {
return mergeWith(mergeDeepLeft)(left)(right)
}
return left
}
}
| krainboltgreene/ramda-extra.js | package/mergeDeepLeft/index.js | JavaScript | isc | 506 |
var map = new maptalks.Map('map', {
center: [-0.113049, 51.49856],
zoom: 14,
baseLayer: new maptalks.TileLayer('base', {
urlTemplate: '$(urlTemplate)',
subdomains: $(subdomains),
attribution: '$(attribution)'
})
});
var layer = new maptalks.VectorLayer('vector').addTo(map);
var c = map.getCenter();
var line = new maptalks.LineString(
[c.sub(0.01, 0), c],
{
symbol:{
// linear gradient
'lineColor' : {
'type' : 'linear',
'colorStops' : [
[0.00, 'red'],
[1 / 4, 'orange'],
[2 / 4, 'green'],
[3 / 4, 'aqua'],
[1.00, 'white']
]
},
'lineWidth' : 10
}
}).addTo(layer);
var line1 = new maptalks.LineString(
[c.sub(0.015, 0.005), c.sub(0, 0.005)],
{
symbol:{
// radial gradient
'lineColor' : {
'type' : 'radial',
'colorStops' : [
[0.00, 'red'],
[1 / 3, 'orange'],
[2 / 3, 'green'],
[1.00, 'white']
]
},
'lineWidth' : 10
}
}).addTo(layer);
| maptalks/examples | src/style/line-gradient/index.js | JavaScript | mit | 1,071 |
function SpreadsheetParser () {
}
/**
* @see http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data
*/
SpreadsheetParser.prototype.convertCsvToJson = function(csv_data, callback) {
var str_delimiter = ",";
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + str_delimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + str_delimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arr_data = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arr_matches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arr_matches = objPattern.exec(csv_data)) {
// Get the delimiter that was found.
var str_matched_delimiter = arr_matches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (str_matched_delimiter.length && (str_matched_delimiter != str_delimiter)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arr_data.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arr_matches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var str_matched_value = arr_matches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var str_matched_value = arr_matches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arr_data[ arr_data.length - 1 ].push( str_matched_value );
}
callback( arr_data );
};
function JsconfLikeSpreadsheetParser() {
};
JsconfLikeSpreadsheetParser.prototype = new SpreadsheetParser();
JsconfLikeSpreadsheetParser.prototype.constructor = JsconfLikeSpreadsheetParser;
JsconfLikeSpreadsheetParser.prototype.buildSchedule = function(json_array, callback) {
var schedule = {};
var day;
var day_identifier;
var slot;
var locations = [
json_array[0][3],
json_array[0][10]
];
for (var i in json_array) {
var row_data = json_array[i];
if (row_data[0].indexOf('Day') !== -1) {
if (typeof day !== 'undefined') {
schedule[day_identifier] = day;
}
day_identifier = row_data[0].replace(/([\r\n])/, "").replace(/(\s)/, "");
day = [];
}
// maybe we have a new time slot
var matches = row_data[0].match(/([0-9]+).([0-9]+)/);
if (null != matches) {
if (isNaN(row_data[1]) || row_data[1].length == 0) {
var end_string = 'Open End';
} else {
var end = matches[1] * 60 + parseInt(matches[2]) + parseInt(row_data[1]);
var end_string = Math.floor(end / 60).toString() + ':' + ((end % 60).toString() == 0 ? '00' : (end % 60).toString());
}
slot = {
time: {
start: matches[1] + ':' + matches[2],
end: end_string
},
talks: []
};
if (row_data[5] == '') {
slot.talks.push({
speaker: 'all',
topic: row_data[4],
location: locations[0]
});
} else {
slot.talks.push({
speaker: row_data[4],
topic: row_data[5],
location: locations[0]
});
}
// There are two talks
if (row_data[0] === row_data[7] && row_data[7] !== '' && row_data[12] !== '') {
slot.talks.push({
speaker: row_data[11],
topic: row_data[12],
location: locations[1]
});
}
}
if (typeof slot != 'undefined') {
day.push(slot);
}
slot = undefined;
}
callback(JSON.stringify(schedule));
};
| glaubinix/conference-schedule | js/spreadsheet-parser.js | JavaScript | mit | 3,842 |
'use strict';
var React = require('react')
var assign = require('object-assign')
var normalize = require('react-style-normalizer')
var EVENT_NAMES = require('react-event-names')
var TEXT_ALIGN_2_JUSTIFY = {
right: 'flex-end',
center: 'center'
}
function copyProps(target, source, list){
list.forEach(function(name){
if (name in source){
target[name] = source[name]
}
})
}
module.exports = React.createClass({
displayName: 'ReactDataGrid.Cell',
propTypes: {
className : React.PropTypes.string,
textPadding: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
]),
style : React.PropTypes.object,
text : React.PropTypes.any,
rowIndex : React.PropTypes.number
},
getDefaultProps: function(){
return {
text: '',
defaultClassName: 'z-cell'
}
},
render: function(){
var props = this.props
var columns = props.columns
var index = props.index
var column = columns? columns[index]: null
var className = props.className || ''
var textAlign = column && column.textAlign
var text = props.renderText?
props.renderText(props.text, column, props.rowIndex):
props.text
var textCellProps = {
className: 'z-text',
style : {padding: props.textPadding, margin: 'auto 0'}
}
var textCell = props.renderCell?
props.renderCell(textCellProps, text, props):
React.DOM.div(textCellProps, text)
if (!index){
className += ' z-first'
}
if (columns && index == columns.length - 1){
className += ' z-last'
}
if (textAlign){
className += ' z-align-' + textAlign
}
className += ' ' + props.defaultClassName
var sizeStyle = column && column.sizeStyle
var cellProps = {
className: className,
style : normalize(assign({}, props.style, sizeStyle))
}
copyProps(cellProps, props, [
'onMouseOver',
'onMouseOut',
'onClick'
].concat([
EVENT_NAMES.onMouseDown,
EVENT_NAMES.onMouseUp
]))
var innerStyle = props.innerStyle
if (textAlign){
innerStyle = assign({}, innerStyle, {justifyContent: column.style.justifyContent || TEXT_ALIGN_2_JUSTIFY[column.textAlign]})
}
var c = React.createElement("div", {className: "z-inner", style: innerStyle},
textCell
)
// var c = textCell
return (
React.createElement("div", React.__spread({}, cellProps),
c,
props.children
)
)
}
}) | gitoneman/react-soc | node_modules/react-datagrid/lib/Cell/index.js | JavaScript | mit | 2,995 |
module.exports = function () {
bot.on("ready", function () {
console.log("[EVENT] Ready: Connected...");
bot.roomRegister(config.roomId);
//writeConfigState();
});
};
| avatarkava/BeavisBot | events/ready.js | JavaScript | mit | 184 |
const request = require('request');
const crypto = require('crypto');
const data = require('./data/pull-request.json');
const headers = require('./data/pull-request-headers.json');
const secret = 'thisIsSecret';
const sig = crypto.createHmac('sha1', secret).update(JSON.stringify(data)).digest('hex');
headers['X-Hub-Signature'] = `sha1=${sig}`;
const options = {
url: 'http://localhost:6500/webhooks/github',
method: 'POST',
headers: headers,
json: data
};
request(options, (err, response, body) => {
if (err) {
console.error(err);
} else {
console.log('Done.');
}
});
| Izak88/abstruse | tests/dev-scripts/pull-request.js | JavaScript | mit | 595 |
import jQuery from 'jquery';
import _ from 'underscore';
(function($) {
var creatingMethods = [
'reinit', 'reactivate', 'activate', 'activateAsLandingPage', 'preload', 'prepare', 'linkedPages'
];
var ignoredMethods = [
'cleanup', 'refreshScroller', 'resize', 'deactivate', 'unprepare',
'isPageChangeAllowed'
];
var prototype = {
_create: function() {
this.configuration = this.element.data('configuration') || this.options.configuration;
this.index = this.options.index;
},
_destroy: function() {
this.isDestroyed = true;
},
_ensureCreated: function() {
this.created = true;
this.element.nonLazyPage(this.options);
},
_delegateToInner: function(method, args) {
return this.element.nonLazyPage.apply(this.element, [method].concat([].slice.call(args)));
},
getPermaId: function() {
return parseInt(this.element.attr('id'), 10);
},
getConfiguration: function() {
return this.configuration;
},
update: function(configuration) {
if (this.created) {
this._delegateToInner('update', arguments);
}
else {
_.extend(this.configuration, configuration.attributes);
}
}
};
_(creatingMethods).each(function(method) {
prototype[method] = function() {
this._ensureCreated();
return this._delegateToInner(method, arguments);
};
});
_(ignoredMethods).each(function(method) {
prototype[method] = function() {
if (this.created) {
return this._delegateToInner(method, arguments);
}
};
});
$.widget('pageflow.page', prototype);
}(jQuery));
| tf/pageflow | entry_types/paged/packages/pageflow-paged/src/frontend/Slideshow/lazyPageWidget.js | JavaScript | mit | 1,656 |
'use strict';
angular.module('copayApp.services')
.factory('legacyImportService', function($rootScope, $log, $timeout, $http, lodash, bitcore, bwcService, sjcl, profileService) {
var root = {};
var wc = bwcService.getClient();
root.getKeyForEmail = function(email) {
var hash = bitcore.crypto.Hash.sha256ripemd160(new bitcore.deps.Buffer(email)).toString('hex');
$log.debug('Storage key:' + hash);
return 'profile::' + hash;
};
root.getKeyForWallet = function(id) {
return 'wallet::' + id;
};
root._importOne = function(user, pass, walletId, get, cb) {
get(root.getKeyForWallet(walletId), function(err, blob) {
if (err) {
$log.warn('Could not fetch wallet: ' + walletId + ":" + err);
return cb('Could not fetch ' + walletId);
}
profileService.importLegacyWallet(user, pass, blob, cb);
});
};
root._doImport = function(user, pass, get, cb) {
var self = this;
get(root.getKeyForEmail(user), function(err, p) {
if (err || !p)
return cb(err || ('Could not find profile for ' + user));
var ids = wc.getWalletIdsFromOldCopay(user, pass, p);
if (!ids)
return cb('Could not find wallets on the profile');
$rootScope.$emit('Local/ImportStatusUpdate',
'Found ' + ids.length + ' wallets to import:' + ids.join());
$log.info('Importing Wallet Ids:', ids);
var i = 0;
var okIds = [];
var toScanIds = [];
lodash.each(ids, function(walletId) {
$timeout(function() {
$rootScope.$emit('Local/ImportStatusUpdate',
'Importing wallet ' + walletId + ' ... ');
self._importOne(user, pass, walletId, get, function(err, id, name, existed) {
if (err) {
$rootScope.$emit('Local/ImportStatusUpdate',
'Failed to import wallet ' + (name || walletId));
} else {
okIds.push(walletId);
$rootScope.$emit('Local/ImportStatusUpdate',
'Wallet ' + id + '[' + name + '] imported successfully');
if (!existed) {
$log.info('Wallet ' + walletId + ' was created. need to be scanned');
toScanIds.push(id);
}
}
if (++i == ids.length) {
return cb(null, okIds, toScanIds);
}
});
}, 100);
});
});
};
root.import = function(user, pass, serverURL, fromCloud, cb) {
var insightGet = function(key, cb) {
var kdfbinary = function(password, salt, iterations, length) {
iterations = iterations || defaultIterations;
length = length || 512;
salt = sjcl.codec.base64.toBits(salt || defaultSalt);
var hash = sjcl.hash.sha256.hash(sjcl.hash.sha256.hash(password));
var prff = function(key) {
return new sjcl.misc.hmac(hash, sjcl.hash.sha1);
};
return sjcl.misc.pbkdf2(hash, salt, iterations, length, prff);
};
var salt = 'jBbYTj8zTrOt6V';
var iter = 1000;
var SEPARATOR = '|';
var kdfb = kdfbinary(pass + SEPARATOR + user, salt, iter);
var kdfb64 = sjcl.codec.base64.fromBits(kdfb);
var keyBuf = new bitcore.deps.Buffer(kdfb64);
var passphrase = bitcore.crypto.Hash.sha256sha256(keyBuf).toString('base64');
var authHeader = new bitcore.deps.Buffer(user + ':' + passphrase).toString('base64');
var retrieveUrl = serverURL + '/retrieve';
var getParams = {
method: 'GET',
url: retrieveUrl + '?key=' + encodeURIComponent(key) + '&rand=' + Math.random(),
headers: {
'Authorization': authHeader,
},
};
$log.debug('Insight GET', getParams);
$http(getParams)
.success(function(data) {
data = JSON.stringify(data);
$log.info('Fetch from insight OK:' + getParams.url);
return cb(null, data);
})
.error(function() {
$log.warn('Failed to fetch from insight');
return cb('PNOTFOUND: Profile not found');
});
};
var localStorageGet = function(key, cb) {
var v = localStorage.getItem(key);
return cb(null, v);
};
var get = fromCloud ? insightGet : localStorageGet;
root._doImport(user, pass, get, cb);
};
return root;
});
| GeopaymeEE/btcpaysme | src/js/services/legacyImportService.js | JavaScript | mit | 4,556 |
/* Copyright © 2013-2018 Richard Rodger and other contributors, MIT License. */
'use strict'
var Assert = require('assert')
var { Gex } = require('gex')
var Lab = require('@hapi/lab')
var lab = (exports.lab = Lab.script())
var describe = lab.describe
var assert = Assert
var testopts = { log: 'silent' }
var Shared = require('./shared')
var it = Shared.make_it(lab)
var Seneca = require('..')
describe('delegation', function () {
it('happy', function (fin) {
var si = Seneca().test(fin)
si.add({ c: 'C' }, function (msg, reply) {
reply(msg)
})
var sid = si.delegate({ a$: 'A', b: 'B' })
assert.ok(Gex('Seneca/*.*.*/*').on(si.toString()))
assert.ok(Gex('Seneca/*.*.*/*/{b:B}').on(sid.toString()))
si.act({ c: 'C' }, function (err, out) {
assert.ok(!err)
assert.ok(out.c === 'C')
sid.act({ c: 'C' }, function (err, out) {
assert.ok(!err)
assert.ok(out.c === 'C')
assert.ok(out.b === 'B')
si.close(fin)
})
})
})
it('dynamic', function (fin) {
var si = Seneca.test(fin)
si.add({ c: 'C' }, function (msg, reply) {
reply(msg)
})
si.add({ d: 'D' }, function (msg, reply) {
this.act({ c: 'C', d: 'D' }, reply)
})
var sid = si.delegate({ a$: 'A', b: 'B' })
si.act({ c: 'C' }, function (err, out) {
assert.ok(!err)
assert.ok(out.c === 'C')
si.act({ d: 'D' }, function (err, out) {
assert.ok(!err)
assert.ok(out.c === 'C')
assert.ok(out.d === 'D')
sid.act({ c: 'C' }, function (err, out) {
assert.ok(!err)
assert.ok(out.c === 'C')
assert.ok(out.b === 'B')
sid.act({ d: 'D' }, function (err, out) {
assert.ok(!err)
assert.ok(out.b === 'B')
assert.ok(out.c === 'C')
assert.ok(out.d === 'D')
sid.close(si.close.bind(si, fin))
})
})
})
})
})
it('prior.basic', function (fin) {
var si = Seneca().test(fin)
si.add({ c: 'C' }, function c0(msg, reply) {
msg.a = 1
reply(msg)
})
si.add({ c: 'C' }, function c1(msg, reply) {
this.prior(msg, function (err, out) {
out.p = 2
reply(err, out)
})
})
si.act({ c: 'C' }, function (err, out) {
assert.equal(err, null)
assert.equal(out.a, 1)
assert.equal(out.p, 2)
si.close(fin)
})
})
it('parent.plugin', function (fin) {
var si = Seneca.test(fin)
si.use(function () {
this.add({ a: 'A' }, function (msg, reply) {
this.log.debug('P', '1')
msg.p1 = 1
reply(msg)
})
return { name: 'p1' }
})
si.act({ a: 'A' }, function (err, out) {
assert.ok(!err)
assert.ok(out.a === 'A')
assert.ok(out.p1 === 1)
si.use(function () {
this.add({ a: 'A' }, function (msg, reply) {
this.log.debug('P', '2a')
this.prior(msg, function (err, out) {
this.log.debug('P', '2b')
out.p2 = 1
reply(err, out)
})
})
return { name: 'p2' }
})
si.act({ a: 'A' }, function (err, out) {
assert.ok(!err)
assert.ok(out.a === 'A')
assert.ok(out.p1 === 1)
assert.ok(out.p2 === 1)
si.use(function () {
this.add({ a: 'A' }, function (msg, reply) {
this.log.debug('P', '3a')
this.prior(msg, function (err, out) {
this.log.debug('P', '3b')
out.p3 = 1
reply(err, out)
})
})
return { name: 'p3' }
})
si.act({ a: 'A' }, function (err, out) {
assert.ok(!err)
assert.ok(out.a === 'A')
assert.ok(out.p1 === 1)
assert.ok(out.p2 === 1)
assert.ok(out.p3 === 1)
si.close(fin)
})
})
})
})
})
| senecajs/seneca | test/delegation.test.js | JavaScript | mit | 3,933 |
module.exports = {
name: 'BulkEditMemo',
type: 'checkbox',
default: true,
section: 'accounts',
title: 'Bulk Edit Memo',
description: 'Adds option to edit memo on transactions to the edit menu.',
};
| dbaldon/toolkit-for-ynab | src/extension/features/accounts/bulk-edit-memo/settings.js | JavaScript | mit | 210 |
// vuex/modules/login.js
import {
SET_MESSAGETYPES,
TOGGLE_ROUTER,
INCREASE_COUNT,
DECREASE_COUNT
} from '../mutation-types'
// initial state
const state = {
messageTypes: [],
router: {
isAll: true,
isRead: false,
isUnRead: false,
isType: false
}
}
// mutations
const mutations = {
[SET_MESSAGETYPES](state, mesTypes, docs) {
if (mesTypes == null) {
state.messageTypes = [];
} else {
for (var i = 0; i < mesTypes.length; i++) {
state.messageTypes.push({
id: i + 1,
title: mesTypes[i],
count: docs[i].count,
selected: false
})
}
}
},
[TOGGLE_ROUTER](state, route, mesTypes, messageType) {
for (let key in state.router) {
key == route ? state.router[key] = true : state.router[key] = false;
for (let i in mesTypes) {
state.messageTypes[i].selected = false;
}
}
if (route == 'isType') {
for (let j in mesTypes) {
j == messageType.id - 1 ? state.messageTypes[j].selected = true : state.messageTypes[j].selected = false;
}
}
},
[INCREASE_COUNT](state, typeid) {
console.log('+1');
state.messageTypes[typeid - 1].count += 1;
},
[DECREASE_COUNT](state, typeid) {
console.log('-1');
state.messageTypes[typeid - 1].count -= 1;
}
}
export default {
state,
mutations
}
| dongjiqiang/message-box | app/vuex/modules/sidebar.js | JavaScript | mit | 1,375 |
var StringMap = (function() {
function StringMap() {
this._values = {};
};
var pt = StringMap.prototype;
pt.get = function (key) {
var value = this._values[key];
return value != null ? value : null;
};
pt.set = function (key, value) {
if (key instanceof Object) {
for(var prop in key) {
this._values[prop] = key[prop];
}
} else {
this._values[key] = value;
}
};
pt.exists = function (key) {
return this._values[key] != null;
};
pt.remove = function (key) {
if (this.exists(key)) {
return delete this._values[key];
}
return false;
};
pt.keys = function () {
var keys = [];
for(var prop in this._values) {
if (this.exists(prop)) {
keys.push(prop);
}
}
return keys;
};
pt.toString = function (formatted, ident) {
if (formatted) {
return JSON.stringify(this._values, null, ident || '\t');
}
return JSON.stringify(this._values);
};
return StringMap;
})();
| Sakee/sakee-framework | src/sakee/libs/string-map.js | JavaScript | mit | 1,018 |
import {
useEntryStructure,
useChapters,
useSection,
useSectionContentElements,
watchCollections
} from 'entryState';
import {ScrolledEntry} from 'editor/models/ScrolledEntry';
import {factories} from 'pageflow/testHelpers';
import {renderHookInEntry, normalizeSeed} from 'support';
const chaptersSeed = [
{
id: 1,
permaId: 10,
position: 1,
configuration: {
title: 'Chapter 1',
summary: 'An introductory chapter'
}
},
{
id: 2,
permaId: 11,
position: 2,
configuration: {
title: 'Chapter 2',
summary: 'A great chapter'
}
}
];
const sectionsSeed = [
{
id: 1,
permaId: 101,
chapterId: 1,
position: 1,
configuration: {
transition: 'scroll'
}
},
{
id: 2,
permaId: 102,
chapterId: 2,
position: 2,
configuration: {
transition: 'fade'
}
}
];
const contentElementsSeed = [
{
id: 1,
permaId: 1001,
sectionId: 1,
typeName: 'heading',
configuration: {
children: 'Heading'
}
},
{
id: 2,
permaId: 1002,
sectionId: 1,
typeName: 'textBlock',
configuration: {
children: 'Some text'
}
},
{
id: 3,
permaId: 1003,
sectionId: 2,
typeName: 'image',
configuration: {
position: 'sticky',
imageId: 4
}
},
{
id: 4,
permaId: 1004,
sectionId: 2,
typeName: 'textBlock',
configuration: {
children: 'Some more text'
}
}
];
describe('useEntryStructure', () => {
const expectedEntryStructure = [
{
title: 'Chapter 1',
chapterSlug: 'chapter-1',
summary: 'An introductory chapter',
sections: [
{
permaId: 101,
previousSection: undefined,
nextSection: {permaId: 102},
sectionIndex: 0,
transition: 'scroll'
}
],
},
{
title: 'Chapter 2',
chapterSlug: 'chapter-2',
summary: 'A great chapter',
sections: [
{
permaId: 102,
previousSection: {permaId: 101},
nextSection: undefined,
sectionIndex: 1,
transition: 'fade'
}
]
}
];
it('reads data from watched collections', () => {
const {result} = renderHookInEntry(() => useEntryStructure(), {
setup: dispatch =>
watchCollections(
factories.entry(ScrolledEntry, {}, {
entryTypeSeed: normalizeSeed({
chapters: chaptersSeed,
sections: sectionsSeed,
contentElements: contentElementsSeed
})
}),
{dispatch}
)
});
const entryStructure = result.current;
expect(entryStructure).toMatchObject(expectedEntryStructure);
});
it('reads data from seed', () => {
const {result} = renderHookInEntry(
() => useEntryStructure(),
{
seed: {
chapters: chaptersSeed,
sections: sectionsSeed,
contentElements: contentElementsSeed
}
}
);
const entryStructure = result.current;
expect(entryStructure).toMatchObject(expectedEntryStructure);
});
});
describe('useSection', () => {
const expectedSection = {
transition: 'scroll'
};
it('returns data for one scene', () => {
const {result} = renderHookInEntry(
() => useSection({sectionPermaId: 101}),
{
seed: {
chapters: chaptersSeed,
sections: sectionsSeed,
contentElements: contentElementsSeed
}
}
);
const section = result.current;
expect(section).toMatchObject(expectedSection);
});
});
describe('useChapters', () => {
it('returns data for all chapters', () => {
const {result} = renderHookInEntry(
() => useChapters(),
{
seed: {
chapters: chaptersSeed
}
}
);
const chapters = result.current;
expect(chapters).toMatchObject([
{
permaId: 10,
chapterSlug: 'chapter-1',
title: 'Chapter 1',
summary: 'An introductory chapter'
},
{
permaId: 11,
chapterSlug: 'chapter-2',
title: 'Chapter 2',
summary: 'A great chapter'
}
]);
});
it('sanitizes chapter titles', () => {
const {result} = renderHookInEntry(
() => useChapters(),
{
seed: {
chapters: [
{
configuration: {
title: 'SmallCase',
}
},
{
configuration: {
title: 'RemöveUmläütß',
}
},
{
configuration: {
title: 'remove space',
}
},
{
configuration: {
title: 'remove#special$character',
}
},
]
}
}
);
const chapters = result.current;
expect(chapters).toMatchObject([
{
chapterSlug: "smallcase",
},
{
chapterSlug: 'remoeveumlaeuetss',
},
{
chapterSlug: 'remove-space',
},
{
chapterSlug: 'removespecialdollarcharacter',
}
]);
});
});
describe('useSectionContentElements', () => {
const expectedContentElements = [
{
id: 3,
permaId: 1003,
type: 'image',
position: 'sticky',
props: {
imageId: 4
}
},
{
id: 4,
permaId: 1004,
type: 'textBlock',
props: {
children: 'Some more text'
}
}
];
it('returns list of content elements of section', () => {
const {result} = renderHookInEntry(
() => useSectionContentElements({sectionId: 2}),
{
seed: {
chapters: chaptersSeed,
sections: sectionsSeed,
contentElements: contentElementsSeed
}
}
);
const contentElements = result.current;
expect(contentElements).toMatchObject(expectedContentElements);
});
});
| tf/pageflow | entry_types/scrolled/package/spec/entryState/structure-spec.js | JavaScript | mit | 6,045 |
/**
* Module dependencies
*/
var fs = require('fs');
var path = require('path');
var _ = require('@sailshq/lodash');
var chalk = require('chalk');
var machine = require('machine');
var loadHelpers = require('./private/load-helpers');
var iterateHelpers = require('./private/iterate-helpers');
/**
* Helpers hook
*/
module.exports = function(sails) {
// Private variable used below to keep track of whether a compatibility
// warning message might need to be displayed.
var _prereleaseCompatWarning;
return {
defaults: {
helpers: {
// Custom usage/miscellaneous options:
usageOpts: {
arginStyle: 'serial',
execStyle: 'natural'
},
// Experimental: Programmatically provide a dictionary of helpers.
moduleDefinitions: undefined,
}
},
configure: function() {
// Check SVR of the `sails` dep in this app's package.json file.
//
// If it points at a 1.0 prerelease less than `1.0.0-44`, then log a warning
// explaining what's going on with helpers (we needed to make a breaking
// change in a prerelease), and that the old way can be achieved through
// configuration. Also mention that, to avoid breaking this app, we've
// applied the old configuration automatically, but that if the SVR in the
// package.json is changed, then this protection will disappear, and this
// app will potentially break.
//
// To resolve this, either:
// • (A) configure `sails.config.helpers.usageOpts` as `{arginStyle: 'named', execStyle: 'deferred'}`
// • or (B) change any code in this app that invokes helpers to take advantage of the new default style
// of usage, then upgrade to the latest version of Sails v1.0 and update
// your package.json file accordingly to make this warning go away.
if (sails.config.helpers.usageOpts.arginStyle !== 'named' || sails.config.helpers.usageOpts.execStyle !== 'deferred') {
var localSailsSVR = (function _gettingSVROfLocalSailsDep(){
var pjPath = path.resolve(sails.config.appPath, 'package.json');
var rawPjText;
try {
rawPjText = fs.readFileSync(pjPath, 'utf8');
} catch (unusedErr) {}
var appPj;
try {
appPj = JSON.parse(rawPjText);
} catch (unusedErr) {}
return appPj && appPj.dependencies && appPj.dependencies.sails;
})();//†
var prerelease = localSailsSVR && localSailsSVR.match(/1\.0\.0\-(.+)$/);
prerelease = prerelease && prerelease[1];
var isMinSVRPointedAtSensitiveV1Prerelease = prerelease && Number(prerelease) < 44;
if (isMinSVRPointedAtSensitiveV1Prerelease) {
sails.config.helpers.usageOpts.arginStyle = 'named';
sails.config.helpers.usageOpts.execStyle = 'deferred';
// Note that we don't actually log the warning right now-- we won't do that
// until a bit later, in .initialize(). Even then, we'll only actually log
// the warning if there are helpers defined in the app. (Because if there
// aren't any helpers, logging a warning would just be annoying!)
_prereleaseCompatWarning =
'---------------------------------------------------------------------\n'+
'Based on its package.json file, it looks like this app was built\n'+
'using the Sails beta, but with a version prior to v1.0.0-44.\n'+
'(This app depends on sails@'+localSailsSVR+'.)\n'+
'\n'+
'In the 1.0.0-44 prerelease of Sails, changes were introduced. By\n'+
'default, helpers now expect serial arguments instead of a dictionary\n'+
'of named parameters. In other words, you\'d now call:\n'+
' await sails.helpers.passwords.changePassword(\'abc123\')\n'+
'Instead of:\n'+
' await sails.helpers.passwords.changePassword({password:\'abc123\'})\n'+
'\n'+
'Additionally, it is no longer necessary to call .now() or .execSync()\n'+
'for synchronous helpers-- by default they are invoked automatically.\n'+
'(Not a fan? Sorry about the inconvenience! And don\'t worry, it\'s\n'+
'easy to change.)\n'+
'\n'+
'To avoid breaking this app, some special settings that make Sails\n'+
'backwards-compatible have been set automatically for you. But please\n'+
'be sure to take the steps below to resolve this as soon as possible.\n'+
'(What if you forgot about this and changed your package.json file?\n'+
'You might inadvertently remove this compatibility check... And if\n'+
'that were to happen, the next time you tried to lift your app, your\n'+
'helpers would no longer work!)\n'+
'\n'+
'To resolve this, use one of the following solutions:\n'+
'\n'+
' (A) <<<<Quick & dirty>>>>\n'+
' If you need a quick fix, or you just prefer to call helpers the old\n'+
' way, no problem: just nestle this in your .sailsrc file:\n'+
' "helpers": {\n'+
' "usageOpts": {\n'+
' "arginStyle": "named",\n'+
' "execStyle": "deferred"\n'+
' }\n'+
' }\n'+
' ^^That will make helpers behave exactly like they did before.\n'+
'\n'+
' (B) <<<<Recommended>>>>\n'+
' Change any relevant code in this app (e.g. `sails.helpers.x({…})`)\n'+
' to take advantage of serial usage, or chain on .with({…}). Then, \n'+
' update the `sails` dependency in your package.json file so that it\n'+
' satisfies ^1.0.0-44 or higher.\n'+
'\n'+
' Note: If you go with this approach, it\'s not all or nothing. You\n'+
' you can always use .with() to call a helper with named parameters\n'+
' on a one-off basis. For example:\n'+
' await sails.helpers.changePassword.with({password:\'abc123\'});\n'+
'\n'+
'\n'+
'(To hide this message, apply one of the solutions suggested above.)\n'+
'\n'+
' [?] If you\'re unsure, visit https://sailsjs.com/support\n'+
'---------------------------------------------------------------------\n';
}//fi
}//fi
// Define `sails.helpers` here so that it can potentially be used by other hooks.
// > NOTE: This is NOT `sails.config.helpers`-- this is `sails.helpers`!
// > (As for sails.config.helpers, it's set automatically based on our `defaults above)
sails.helpers = {};
Object.defineProperty(sails.helpers, 'inspect', {
enumerable: false,
configurable: false,
writable: true,
value: function inspect(){
// Tree diagram:
// ```
// .
// ├── …
// │ ├── …
// │ │ └── …
// │ ├── …
// │ └── …
// │
// ├── …
// │ ├── …
// │ │ └── …
// │ ├── …
// │ │ ├── …
// │ │ ├── …
// │ │ └── …
// │ ├── …
// │ └── …
// │
// ├── …
// │ └── …
// │
// ├── …
// ├── …
// └── …
// ```
var treeDiagram = (function(){
var OFFSET = ' ';
var TAB = ' ';
var SYMBOL_INITIAL = '. ';
var SYMBOL_NO_BRANCH = '│ ';
var SYMBOL_MID_BRANCH = '├── ';
var SYMBOL_LAST_BRANCH = '└── ';
var treeDiagram = '';
treeDiagram += OFFSET + SYMBOL_INITIAL + '\n';
iterateHelpers(
sails.helpers,
function _onBeforeStartingPack(pack, key, depth, isFirst, isLast, lastnessPerAncestor){
var indentation = _.reduce(lastnessPerAncestor, function(indentation, wasLast){
if (wasLast) {
indentation += TAB;
} else {
indentation += SYMBOL_NO_BRANCH;
}
return indentation;
}, '');
if (isLast) {
treeDiagram += OFFSET + indentation + SYMBOL_LAST_BRANCH + key + '\n';
} else {
treeDiagram += OFFSET + indentation + SYMBOL_MID_BRANCH + key + '\n';
}
},
undefined,// « no need for an _onAfterFinishingPack notifier here, so we omit it
function _onHelper(callable, methodName, depth, isFirst, isLast, lastnessPerAncestor){
var indentation = _.reduce(lastnessPerAncestor, function(indentation, wasLast){
if (wasLast) {
indentation += TAB;
} else {
indentation += SYMBOL_NO_BRANCH;
}
return indentation;
}, '');
if (isLast) {
treeDiagram += OFFSET + indentation + SYMBOL_LAST_BRANCH + (callable.toJSON()._fromLocalSailsApp ? chalk.bold.cyan(methodName) : chalk.italic(methodName)) + chalk.gray('()')+'\n';
if (depth === 2) {
treeDiagram += OFFSET + indentation + '\n';
}
} else {
treeDiagram += OFFSET + indentation + SYMBOL_MID_BRANCH + (callable.toJSON()._fromLocalSailsApp ? chalk.bold.cyan(methodName) : chalk.italic(methodName)) + chalk.gray('()')+'\n';
}
}
);
return treeDiagram;
})();//†
// Examples (asynchronous and synchronous)
var example1 = (function(){
var exampleArginPhrase = '';
if (sails.config.helpers.usageOpts.arginStyle === 'named') {
exampleArginPhrase = '{dir: \'./colorado/\'}';
} else if (sails.config.helpers.usageOpts.arginStyle === 'serial') {
exampleArginPhrase = '\'./colorado/\'';
}
return 'var contents = await sails.helpers.fs.ls('+exampleArginPhrase+');';
})();//†
var example2 = (function(){
var exampleArginPhrase = '';
if (sails.config.helpers.usageOpts.arginStyle === 'named') {
exampleArginPhrase = '{style: \'url-friendly\'}';
} else if (sails.config.helpers.usageOpts.arginStyle === 'serial') {
exampleArginPhrase = '\'url-friendly\'';
}
if (sails.config.helpers.usageOpts.execStyle === 'deferred') {
return 'var name = sails.helpers.strings.random('+exampleArginPhrase+').now();';
} else if (sails.config.helpers.usageOpts.execStyle === 'immediate' || sails.config.helpers.usageOpts.execStyle === 'natural') {
return 'var name = sails.helpers.strings.random('+exampleArginPhrase+');';
}
throw new Error('Consistency violation: Unrecognized arginStyle/execStyle in sails.config.helpers.usageOpts (This should never happen, since it should have already been validated and prevented from being built- please report at https://sailsjs.com/bugs)');
})();//†
return ''+
'-------------------------------------------------------\n'+
' sails.helpers\n'+
'\n'+
' Available methods:\n'+
treeDiagram+'\n'+
'\n'+
' Example usage:\n'+
' '+example1+'\n'+
' '+example2+'\n'+
'\n'+
' More info:\n'+
' https://sailsjs.com/support\n'+
'-------------------------------------------------------\n';
}//ƒ
});//…)
},
initialize: function(done) {
// Load helpers from the appropriate folder.
loadHelpers(sails, function(err) {
if (err) { return done(err); }
// If deemed relevant, log the prerelease compatibility warning that
// we built above. (Then clear it out, since we don't want to ever
// display it again during this "lift" cycle-- even if the experimental
// .reload() method is in use.)
if (_prereleaseCompatWarning && _.keys(sails.helpers).length > 0) {
sails.log.warn(_prereleaseCompatWarning);
_prereleaseCompatWarning = '';
}
return done();
});//_∏_
},
/**
* @experimental
* (This might change at any time, without a major version release!)
*/
furnishPack: function(slug, packInfo){
packInfo = packInfo || {};
slug = _.map(slug.split('.'), _.kebabCase).join('.');
var slugKeyPath = _.map(slug.split('.'), _.camelCase).join('.');
var chunks = slugKeyPath.split('.');
if (chunks.length > 1) {
sails.log.verbose(
'Watch out! Nesting helpers more than one sub-folder deep can be a liability. '+
'It also means that you\'ll need to type more every time you want to use '+
'your helper. Instead, try keeping your directory structure as flat as possible; '+
'i.e. in general, having more explicit filenames is better than having deep, '+
'complicated folder hierarchies.'
);
}
// If pack already exists, avast.
if (_.get(sails.helpers, slugKeyPath)) {
return;
}
// Ancestor packs:
var thisKeyPath;
var theseChunks;
var parentKeyPath;
var parentPackOrRoot;
for (var i = 0; i < chunks.length - 1; i++) {
theseChunks = chunks.slice(0,i+1);
thisKeyPath = theseChunks.join('.');
parentKeyPath = theseChunks.slice(0, -1).join('.');
if (!_.get(sails.helpers, thisKeyPath)) {
parentPackOrRoot = parentKeyPath ? _.get(sails.helpers, parentKeyPath) : sails.helpers;
parentPackOrRoot[chunks[i]] = machine.pack({
name: 'sails.helpers.'+chunks.slice(0,i+1).join('.'),
defs: {},
customize: _.extend({}, sails.config.helpers.usageOpts, {
implementationSniffingTactic: sails.config.implementationSniffingTactic||undefined
})
});
}
}//∞
// Main pack:
parentKeyPath = chunks.slice(0, -1).join('.');
parentPackOrRoot = parentKeyPath ? _.get(sails.helpers, parentKeyPath) : sails.helpers;
parentPackOrRoot[chunks[chunks.length - 1]] = machine.pack(_.extend({}, packInfo, {
name: 'sails.helpers.'+slugKeyPath,
customize: _.extend({}, sails.config.helpers.usageOpts, {
implementationSniffingTactic: sails.config.implementationSniffingTactic||undefined
})
}));
},
/**
* @experimental
* (This might change at any time, without a major version release!)
*/
furnishHelper: function(identityPlusMaybeSlug, nmDef){
// Ensure we're starting off with dot-delimited, kebab-cased hops.
identityPlusMaybeSlug = _.map(identityPlusMaybeSlug.split('.'), _.kebabCase).join('.');
var chunks = identityPlusMaybeSlug.split('.');
// slug ('foo-bar.baz-bing.beep.boop')
// identity ('do-something')
var slug = chunks.length >= 2 ? chunks.slice(0, -1).join('.') : undefined;
var identity = _.last(chunks);
// Camel-case every part of the file path, and join with dots
// e.g. admin-stuff.foo.do-something => adminStuff.foo.doSomething
var slugKeyPath = slug ? _.map(slug.split('.'), _.camelCase).join('.') : undefined;
var fullKeyPath = slug ? slugKeyPath + '.' + machine.getMethodName(identity) : machine.getMethodName(identity);
if (!_.get(sails.helpers, fullKeyPath)) {
// Work our way down
if (slug && !_.get(sails.helpers, slugKeyPath)) {
this.furnishPack(slug, {
name: 'sails.helpers.'+slugKeyPath,
defs: {}
});
}//fi
// And then build the helper last
// > (can't do it first! We'd confuse `_.get()`!)
// Use provided `identity` if no explicit identity was set.
// (Otherwise, as of machine@v15, this could fail with an ImplementationError.)
if (!nmDef.identity) {
nmDef.identity = identity;
}
// Attach new method to the appropriate pack.
// e.g. sails.helpers.userHelpers.foo.myHelper
if (slug) {
var parentPack = _.get(sails.helpers, slugKeyPath);
parentPack.registerDefs(
(function(){
var defs = {};
defs[identity] = nmDef;
return defs;
})()//†
);
} else {
sails.helpers[machine.getMethodName(identity)] = machine.buildWithCustomUsage(_.extend(
{},
sails.config.helpers.usageOpts,
{
def: nmDef,
implementationSniffingTactic: sails.config.implementationSniffingTactic
}
));
}
}//fi
},
/**
* sails.hooks.helpers.reload()
*
* @param {Dictionary?} helpers [if specified, these helpers will replace all existing helpers. Otherwise, if omitted, helpers will be freshly reloaded from disk, and old helpers will be thrown away.]
* @param {Function} done [optional callback]
*
* @experimental
* (This might change at any time, without a major version release!)
*/
reload: function(helpers, done) {
// Handle variadic usage
if (typeof helpers === 'function') {
done = helpers;
helpers = undefined;
}
// Handle optional callback
done = done || function _noopCb(err){
if (err) {
sails.log.error('Could not reload helpers due to an error:', err, '\n(continuing anyway...)');
}
};//ƒ
// If we received an explicit set of helpers to load, use them.
// Otherwise reload helpers from the appropriate folder.
if (helpers) {
sails.helpers = helpers;
return done();
} else {
return loadHelpers(sails, done);
}
}//ƒ
};
};
| balderdashy/sails | lib/hooks/helpers/index.js | JavaScript | mit | 18,583 |
;(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
}
else if (typeof exports === 'object') {
module.exports = factory(require("jquery"));
}
else {
factory(jQuery);
}
}
(function($) {
var pluginName = "tinycircleslider"
, defaults = {
interval: false
, intervalTime: 3500
, dotsSnap: false
, dotsHide: true
, radius: 140
, start: 0
}
;
function Plugin($container, options) {
/**
* The options of the carousel extend with the defaults.
*
* @property options
* @type Object
* @default defaults
*/
this.options = $.extend({}, defaults, options);
/**
* @property _defaults
* @type Object
* @private
* @default defaults
*/
this._defaults = defaults;
/**
* @property _name
* @type String
* @private
* @final
* @default 'tinycircleslider'
*/
this._name = pluginName;
var self = this
, $viewport = $container.find(".viewport")
, $overview = $container.find(".overview")
, $slides = $overview.children()
, $thumb = $container.find(".thumb")
, $dots = $container.find(".dot")
, $links = $slides.find("a")
, containerSize = {
width: $container.outerWidth(true)
, height: $container.outerHeight(true)
}
, slideSize = {
width: $slides.first().outerWidth(true)
, height: $slides.first().outerHeight(true)
}
, thumbSize = {
width: $thumb.outerWidth(true)
, height: $thumb.outerHeight(true)
}
, dotSize = {
width: $dots.outerWidth()
, height: $dots.outerHeight()
}
, intervalTimer = null
, animationTimer = null
, touchEvents = 'ontouchstart' in window
, isTouchEvent = false
, hasRequestAnimationFrame = 'requestAnimationFrame' in window
;
/**
* When dotsSnap is enabled every slide has a corresponding dot.
*
* @property dots
* @type Array
* @default []
*/
this.dots = [];
/**
* The index of the current slide.
*
* @property slideCurrent
* @type Number
* @default 0
*/
this.slideCurrent = 0;
/**
* The current angle in degrees
*
* @property angleCurrent
* @type Number
* @default 0
*/
this.angleCurrent = 0;
/**
* The number of slides the slider is currently aware of.
*
* @property slidesTotal
* @type Number
* @default 0
*/
this.slidesTotal = $slides.length;
/**
* If the interval is running the value will be true.
*
* @property intervalActive
* @type Boolean
* @default false
*/
this.intervalActive = false;
/**
* @method _initialize
* @private
*/
function _initialize() {
_setDots();
$overview
.append($slides.first().clone())
.css("width", slideSize.width * ($slides.length + 1));
_setEvents();
_setCSS(0);
self.move(self.options.start, self.options.interval);
return self;
}
/**
* @method _setEvents
* @private
*/
function _setEvents() {
if (touchEvents) {
$container[0].ontouchstart = _startDrag;
$container[0].ontouchmove = _drag;
$container[0].ontouchend = _endDrag;
}
$thumb.bind("mousedown", _startDrag);
var snapHandler = function (event) {
event.preventDefault();
event.stopImmediatePropagation();
self.stop();
self.move($(this).attr("data-slide-index"));
return false;
};
if (touchEvents) {
$container.delegate(".dot", "touchstart", snapHandler);
}
$container.delegate(".dot", "mousedown", snapHandler);
}
/**
* @method _setTimer
* @private
*/
function _setTimer(slideFirst) {
intervalTimer = setTimeout(function() {
self.move(self.slideCurrent + 1, true);
}, (slideFirst ? 50 : self.options.intervalTime));
}
/**
* @method _toRadians
* @private
* @param {Number} [degrees]
*/
function _toRadians(degrees) {
return degrees * (Math.PI / 180);
}
/**
* @method _toDegrees
* @private
* @param {Number} [radians]
*/
function _toDegrees(radians) {
return radians * 180 / Math.PI;
}
/**
* @method _setDots
* @private
*/
function _setDots() {
var docFragment = document.createDocumentFragment();
$dots.remove();
$slides.each(function(index, slide) {
var $dotClone = null
, angle = parseInt($(slide).attr("data-degrees"), 10) || (index * 360 / self.slidesTotal)
, position = {
top: -Math.cos(_toRadians(angle)) * self.options.radius + containerSize.height / 2 - dotSize.height / 2
, left: Math.sin(_toRadians(angle)) * self.options.radius + containerSize.width / 2 - dotSize.width / 2
}
;
if($dots.length > 0) {
$dotClone = $dots.clone();
$dotClone
.addClass($(slide).attr("data-classname"))
.css(position);
docFragment.appendChild($dotClone[0]);
}
self.dots.push({
"angle": angle
, "slide": slide
, "dot": $dotClone
});
});
self.dots.sort(function(dotA, dotB) {
return dotA.angle - dotB.angle;
});
$.each(self.dots, function(index, dot) {
if($(dot.dot).length > 0){
$(dot.dot)
.addClass("dot-" + (index + 1))
.attr('data-slide-index', index)
.html("<span>" + (index + 1) + "</span>");
}
});
$container.append(docFragment);
$dots = $container.find(".dot");
}
/**
* If the interval is stopped start it.
*
* @method start
* @chainable
*/
this.start = function(first) {
if(self.options.interval) {
self.intervalActive = true;
_setTimer(first);
}
return self;
};
/**
* If the interval is running stop it.
*
* @method stop
* @chainable
*/
this.stop = function() {
self.intervalActive = false;
clearTimeout(intervalTimer);
return self;
};
/**
* @method _findShortestPath
* @private
* @param {Number} [angleA]
* @param {Number} [angleB]
*/
function _findShortestPath(angleA, angleB) {
var angleCW, angleCCW, angleShortest;
if(angleA > angleB) {
angleCW = angleA - angleB;
angleCCW = -(angleB + 360 - angleA);
}
else {
angleCW = angleA + 360 - angleB;
angleCCW = -(angleB - angleA);
}
angleShortest = angleCW < Math.abs(angleCCW) ? angleCW : angleCCW;
return [angleShortest, angleCCW, angleCW];
}
/**
* @method _findClosestSlide
* @private
* @param {Number} [angle]
*/
function _findClosestSlide(angle) {
var closestDotAngleToAngleCCW = 9999
, closestDotAngleToAngleCW = 9999
, closestDotAngleToAngle = 9999
, closestSlideCCW = 0
, closestSlideCW = 0
, closestSlide = 0
;
$.each(self.dots, function(index, dot) {
var delta = _findShortestPath(dot.angle, angle);
if(Math.abs(delta[0]) < Math.abs(closestDotAngleToAngle)) {
closestDotAngleToAngle = delta[0];
closestSlide = index;
}
if(Math.abs(delta[1]) < Math.abs(closestDotAngleToAngleCCW)) {
closestDotAngleToAngleCCW = delta[1];
closestSlideCCW = index;
}
if(Math.abs(delta[2]) < Math.abs(closestDotAngleToAngleCW)) {
closestDotAngleToAngleCW = delta[2];
closestSlideCW = index;
}
});
return [
[ closestSlide, closestSlideCCW, closestSlideCW ]
, [ closestDotAngleToAngle, closestDotAngleToAngleCCW, closestDotAngleToAngleCW ]
];
}
/**
* Move to a specific slide.
*
* @method move
* @chainable
* @param {Number} [index] The slide to move to.
*/
this.move = function(index) {
var slideIndex = Math.max(0, isNaN(index) ? self.slideCurrent : index);
if(slideIndex >= self.slidesTotal) {
slideIndex = 0;
}
var angleDestination = self.dots[slideIndex] && self.dots[slideIndex].angle
, angleDelta = _findShortestPath(angleDestination, self.angleCurrent)[0]
, angleStep = angleDelta > 0 ? -2 : 2
;
self.slideCurrent = slideIndex;
_stepMove(angleStep, angleDelta, 50);
self.start();
return self;
};
/**
* @method _sanitizeAngle
* @private
* @param {Number} [degrees]
*/
function _sanitizeAngle(degrees) {
return (degrees < 0) ? 360 + (degrees % -360) : degrees % 360;
}
/**
* @method _stepMove
* @private
* @param {Number} [angleStep]
* @param {Number} [angleDelta]
* @param {Boolean} [stepInterval]
*/
function _stepMove(angleStep, angleDelta, stepInterval) {
var angleStepNew = angleStep
, endAnimation = false
;
if(Math.abs(angleStep) > Math.abs(angleDelta)) {
angleStepNew = -angleDelta;
endAnimation = true;
} else if(hasRequestAnimationFrame) {
requestAnimationFrame(function() {
_stepMove(angleStepNew, angleDelta + angleStep);
});
} else {
animationTimer = setTimeout(function() {
_stepMove(angleStepNew, angleDelta + angleStep, stepInterval * 0.9);
}, stepInterval);
}
self.angleCurrent = _sanitizeAngle(self.angleCurrent - angleStepNew);
_setCSS(self.angleCurrent, endAnimation);
}
/**
* @method _page
* @private
* @param {Object} [event]
*/
function _page(event) {
return {
x: isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX),
y: isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY)
};
}
/**
* @method _drag
* @private
* @param {Object} [event]
*/
function _drag(event) {
var containerOffset = $container.offset()
, thumbPositionNew = {
left: _page(event).x - containerOffset.left - (containerSize.width / 2)
, top: _page(event).y - containerOffset.top - (containerSize.height / 2)
}
;
self.angleCurrent = _sanitizeAngle(
_toDegrees(
Math.atan2(thumbPositionNew.left, -thumbPositionNew.top)
)
);
if (!hasRequestAnimationFrame) {
_setCSS(self.angleCurrent);
}
return false;
}
/**
* @method _setCSS
* @private
* @param {Number} [angle]
* @param {Function} [fireCallback]
*/
function _setCSS(angle, fireCallback) {
closestSlidesAndAngles = _findClosestSlide(angle);
closestSlides = closestSlidesAndAngles[0];
closestAngles = closestSlidesAndAngles[1];
$overview.css("left", -(closestSlides[1] * slideSize.width + Math.abs(closestAngles[1]) * slideSize.width / (Math.abs(closestAngles[1]) + Math.abs(closestAngles[2]))));
$thumb.css({
top: -Math.cos(_toRadians(angle)) * self.options.radius + (containerSize.height / 2 - thumbSize.height / 2)
, left: Math.sin(_toRadians(angle)) * self.options.radius + (containerSize.width / 2 - thumbSize.width / 2)
});
if(fireCallback) {
/**
* The move event will trigger when the carousel slides to a new slide.
*
* @event move
*/
$container.trigger("move", [$slides[self.slideCurrent], self.slideCurrent]);
}
}
/**
* @method _endDrag
* @private
* @param {Object} [event]
*/
function _endDrag(event) {
if($(event.target).hasClass("dot")) {
return false;
}
self.dragging = false;
event.preventDefault();
$(document).unbind("mousemove mouseup");
$thumb.unbind("mouseup");
if(self.options.dotsHide) {
$dots.stop(true, true).fadeOut("slow");
}
if(self.options.dotsSnap) {
self.move(_findClosestSlide(self.angleCurrent)[0][0]);
}
}
function _dragAnimationLoop() {
if(self.dragging) {
_setCSS(self.angleCurrent);
requestAnimationFrame(function() {
_dragAnimationLoop();
});
}
}
/**
* @method _startDrag
* @private
* @param {Object} [event]
*/
function _startDrag(event) {
event.preventDefault();
isTouchEvent = event.type == 'touchstart';
self.dragging = true;
if($(event.target).hasClass("dot")) {
return false;
}
self.stop();
$(document).mousemove(_drag);
$(document).mouseup(_endDrag);
$thumb.mouseup(_endDrag);
if(self.options.dotsHide) {
$dots.stop(true, true).fadeIn("slow");
}
if(hasRequestAnimationFrame) {
_dragAnimationLoop();
}
}
return _initialize();
}
/**
* @class tinycircleslider
* @constructor
* @param {Object} options
@param {Boolean} [options.dotsSnap=false] Shows dots when user starts dragging and snap to them.
@param {Boolean} [options.dotsHide=true] Fades out the dots when user stops dragging.
@param {Number} [options.radius=140] Used to determine the size of the circleslider.
@param {Boolean} [options.interval=false] Move to another block on intervals.
@param {Number} [options.intervalTime=intervalTime] Interval time in milliseconds.
@param {Number} [options.start=0] The slide to start with.
*/
$.fn[pluginName] = function(options) {
return this.each(function() {
if(!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin($(this), options));
}
});
};
})); | wieringen/tinycircleslider | lib/jquery.tinycircleslider.js | JavaScript | mit | 16,654 |
import * as defaultOperations from "./operations";
import { createQueryTester, EqualsOperation, createEqualsOperation } from "./core";
var createDefaultQueryTester = function (query, _a) {
var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations;
return createQueryTester(query, {
compare: compare,
operations: Object.assign({}, defaultOperations, operations)
});
};
export { EqualsOperation, createQueryTester, createEqualsOperation };
export * from "./operations";
export default createDefaultQueryTester;
| Hanul/UPPERCASE | node_modules/ubm/node_modules/sift/es5m/index.js | JavaScript | mit | 562 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v7.5c0 .83.67 1.5 1.5 1.5S6 20.33 6 19.5V19h12v.5c0 .82.67 1.5 1.5 1.5.82 0 1.5-.67 1.5-1.5V12l-2.08-5.99zM7.5 16c-.83 0-1.5-.67-1.5-1.5S6.67 13 7.5 13s1.5.67 1.5 1.5S8.33 16 7.5 16zm9 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5.81 10l1.04-3h10.29l1.04 3H5.81z"
}), 'DirectionsCarFilledRounded'); | oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/DirectionsCarFilledRounded.js | JavaScript | mit | 562 |
define(
'vm-speakers-tests-function',
['jquery', 'underscore', 'ko', 'datacontext', 'config', 'filter.speakers', 'sort'],
function ($, _, ko, datacontext, config, filter, sort) {
var doNothing = function(){};
config.useMocks(true); // this helps me NOT mock datacontext
config.currentUserId = 3;
config.currentUser = function() { return { id: function() { return 3; } }; };
config.logger = { success: doNothing };
config.dataserviceInit();
var fakeMessenger = {
publish: { viewModelActivated: doNothing }
};
var fakeRouter = {
navigateBack: doNothing
};
var fakeStore = {
clear: doNothing,
fetch: function (){ return 'John';}, //doNothing,
save: doNothing
};
var findVm = function() {
return window.testFn(ko, _, datacontext, config, fakeRouter, fakeMessenger, filter, sort, fakeStore);
};
module('speakers viewmodel tests');
asyncTest('Activate viewmodel and has speakers',
function() {
//ARRANGE
var vmSpeakers = findVm(),
data = {
persons: ko.observable(),
sessions: ko.observable()
},
routeData = {};
$.when(
datacontext.persons.getSpeakers({ results: data.persons }),
datacontext.sessions.getData({ results: data.sessions })
)
.pipe(datacontext.speakerSessions.refreshLocal)
.done(function () {
//ACT
vmSpeakers.activate(routeData, function () {
//ASSERT
ok(vmSpeakers.speakers().length > 0, 'Speakers exist');
});
})
.always(function () {
start();
});
}
);
asyncTest('Filter viewmodel by Name',
function () {
//ARRANGE
var vmSpeakers = findVm(),
data = {
persons: ko.observable(),
sessions: ko.observable()
},
routeData = {};
//store subscriptions in array
var subscription;
// Because we have a throttle, I can either remove it
// or I can subscribe to the observable.
// This means we have to reshapre our test so it waits
// for the throttle to kick in.
//vmSpeakers.speakerFilter.searchText = ko.observable();
$.when(
datacontext.persons.getSpeakers({ results: data.persons }),
datacontext.sessions.getData({ results: data.sessions })
)
.pipe(datacontext.speakerSessions.refreshLocal)
.done(function() {
//ACT
var performTest = function(val) {
vmSpeakers.activate(routeData, function() {
var speakers = vmSpeakers.speakers();
//ASSERT
var onlyJohn = _.all(speakers, function(item) {
return item.firstName() === 'John';
});
ok(onlyJohn, 'Filtered properly');
// RESET
subscription.dispose();
start();
});
};
subscription = vmSpeakers.speakerFilter.searchText.subscribe(performTest);
vmSpeakers.speakerFilter.searchText('John');
});
}
);
}); | johnpapa/CodeCamper | CodeCamper.Web/test/vm.speakers.tests.js | JavaScript | mit | 3,985 |
const Lab = require('@hapi/lab');
const Hapi = require('@hapi/hapi');
const Sinon = require('sinon');
const JWT = require('jsonwebtoken');
const UserService = require('modules/authorization/services/user');
const LoginCtrl = require('modules/authorization/controllers/login');
const Auth = require('plugins/auth');
const NSError = require('errors/nserror');
const Logger = require('test/fixtures/logger-plugin');
const Config = require('config');
const { beforeEach, describe, expect, it } = (exports.lab = Lab.script());
describe('API Controller: login', () => {
// created using npm run token
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MCwidmVyc2lvbiI6MSwiaWF0IjoxNTI5OTQ4MjgyLCJleHAiOjE1Mjk5NTE4ODIsImF1ZCI6WyJub2lyZTphdXRoIl19.9QZNHh9rn0KFMxmxu8g-3sC4_G0Ompgy28c_DgicljQ';
let server;
beforeEach(async () => {
// make server quiet, 500s are rethrown and logged by default..
server = Hapi.server({ debug: { log: false, request: false } });
await server.register(Logger);
server.route({
method: 'POST',
path: '/login',
config: { handler: LoginCtrl.login, plugins: { stateless: true } }
});
server.route({
method: 'GET',
path: '/logout',
config: { handler: LoginCtrl.logout, plugins: { stateless: true } }
});
server.route({
method: 'GET',
path: '/renew',
config: { handler: LoginCtrl.renew, plugins: { stateless: true } }
});
server.route({
method: 'POST',
path: '/password-reset',
config: { handler: LoginCtrl.passwordReset, plugins: { stateless: true } }
});
server.route({
method: 'POST',
path: '/password-update',
config: { handler: LoginCtrl.passwordUpdate, plugins: { stateless: true } }
});
});
it('rejects login with invalid username', async flags => {
// cleanup
flags.onCleanup = function() {
authenticateStub.restore();
};
// setup
const credentials = { username: 'invalid', password: 'secret' };
const authenticateStub = Sinon.stub(UserService, 'authenticate');
authenticateStub
.withArgs(credentials.username, credentials.password)
.rejects(NSError.AUTH_INVALID_CREDENTIALS());
// exercise
const response = await server.inject({
method: 'POST',
url: '/login',
payload: credentials
});
// validate
expect(authenticateStub.calledOnce).to.be.true();
expect(response.statusCode).to.equal(401);
expect(response.statusMessage).to.equal('Unauthorized');
expect(response.result.message).to.equal(NSError.AUTH_INVALID_CREDENTIALS().message);
});
it('rejects login with invalid password', async flags => {
// cleanup
flags.onCleanup = function() {
authenticateStub.restore();
};
// setup
const credentials = { username: 'test', password: '' };
const authenticateStub = Sinon.stub(UserService, 'authenticate');
authenticateStub
.withArgs(credentials.username, credentials.password)
.rejects(NSError.AUTH_INVALID_CREDENTIALS());
// exercise
const response = await server.inject({
method: 'POST',
url: '/login',
payload: credentials
});
// validate
expect(authenticateStub.calledOnce).to.be.true();
expect(response.statusCode).to.equal(401);
expect(response.statusMessage).to.equal('Unauthorized');
expect(response.result.message).to.equal(NSError.AUTH_INVALID_CREDENTIALS().message);
});
it('handles internal server errors', async flags => {
// cleanup
flags.onCleanup = function() {
authenticateStub.restore();
};
// setup
const credentials = { username: 'test', password: 'test' };
const authenticateStub = Sinon.stub(UserService, 'authenticate');
authenticateStub
.withArgs(credentials.username, credentials.password)
.rejects(NSError.AUTH_ERROR());
// exercise
const response = await server.inject({
method: 'POST',
url: '/login',
payload: credentials
});
expect(authenticateStub.calledOnce).to.be.true();
expect(response.statusCode).to.equal(500);
expect(response.statusMessage).to.equal('Internal Server Error');
expect(response.result.message).to.equal('An internal server error occurred');
});
it('login user with valid credentials', async flags => {
// cleanup
flags.onCleanup = function() {
authenticateStub.restore();
};
// setup
const credentials = { username: 'test', password: 'secret' };
const authenticateStub = Sinon.stub(UserService, 'authenticate');
authenticateStub.withArgs(credentials.username, credentials.password).resolves(token);
// exercise
const response = await server.inject({
method: 'POST',
url: '/login',
payload: credentials
});
expect(authenticateStub.calledOnce).to.be.true();
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.headers['server-authorization']).to.exist();
expect(response.headers['server-authorization']).to.equals(token);
});
it('stores token in cookie if statefull login', async flags => {
// cleanup
flags.onCleanup = function() {
authenticateStub.restore();
};
// setup
server = Hapi.server();
server.route({
method: 'POST',
path: '/login',
config: { handler: LoginCtrl.login, plugins: { stateless: false } }
});
const credentials = { username: 'invalid', password: 'secret' };
const authenticateStub = Sinon.stub(UserService, 'authenticate');
authenticateStub.withArgs(credentials.username, credentials.password).resolves(token);
// exercise
const response = await server.inject({
method: 'POST',
url: '/login',
payload: credentials
});
expect(authenticateStub.calledOnce).to.be.true();
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.headers['set-cookie']).to.be.an.array();
expect(response.headers['set-cookie'][0]).to.be.a.string();
expect(response.headers['set-cookie'][0].startsWith('token=')).to.be.true();
expect(response.headers['set-cookie'][0].indexOf(token)).to.equals('token='.length);
});
it('logout user', async () => {
// exercise
const response = await server.inject({
method: 'GET',
url: '/logout'
});
// validate
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.result.success).to.be.true();
expect(response.result.message).to.equals('logged out');
});
it('removes token from cookie if statefull logout', async () => {
// setup
server = Hapi.server();
server.route({
method: 'GET',
path: '/logout',
config: { handler: LoginCtrl.logout, plugins: { stateless: false } }
});
// exercise
const response = await server.inject({
method: 'GET',
url: '/logout'
});
// validate
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.headers['set-cookie']).to.be.an.array();
expect(response.headers['set-cookie'][0]).to.be.a.string();
expect(response.headers['set-cookie'][0].startsWith('token=;')).to.be.true();
});
it('renews authentication token without type', async () => {
// exercise
const response = await server.inject({
method: 'GET',
url: '/renew',
headers: {
authorization: `${token}`
}
});
// validate
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.headers['server-authorization']).to.exist();
expect(response.headers['server-authorization']).not.to.equals(token);
expect(JWT.decode(response.headers['server-authorization']).id).to.equals(
JWT.decode(token).id
);
expect(JWT.decode(response.headers['server-authorization']).version).to.equal(
Config.auth.version
);
expect(JWT.decode(response.headers['server-authorization']).exp).to.be.a.number();
});
it('renews authentication token with type', async () => {
// exercise
const response = await server.inject({
method: 'GET',
url: '/renew',
headers: {
authorization: `Bearer ${token}`
}
});
// validate
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.headers['server-authorization']).to.exist();
expect(response.headers['server-authorization']).not.to.equals(token);
expect(JWT.decode(response.headers['server-authorization']).id).to.equals(
JWT.decode(token).id
);
expect(JWT.decode(response.headers['server-authorization']).version).to.equal(
Config.auth.version
);
expect(JWT.decode(response.headers['server-authorization']).exp).to.be.a.number();
});
it('sends password reset email', async flags => {
// cleanup
flags.onCleanup = function() {
UserService.sendPasswordResetEmail.restore();
};
// setup
Sinon.stub(UserService, 'sendPasswordResetEmail').resolves();
// exercise
const response = await server.inject({
method: 'POST',
url: '/password-reset',
payload: { email: '' }
});
// validate
expect(UserService.sendPasswordResetEmail.calledOnce).to.be.true();
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.result.success).to.be.true();
expect(response.result.message).to.equals('password reset');
});
it('handles sending password reset email errors', async flags => {
// cleanup
flags.onCleanup = function() {
UserService.sendPasswordResetEmail.restore();
};
// setup
Sinon.stub(UserService, 'sendPasswordResetEmail').rejects();
// exercise
const response = await server.inject({
method: 'POST',
url: '/password-reset',
payload: { email: '' }
});
// validate
expect(UserService.sendPasswordResetEmail.calledOnce).to.be.true();
expect(response.statusCode).to.equal(500);
expect(response.statusMessage).to.equal('Internal Server Error');
expect(response.result.message).to.equal('An internal server error occurred');
});
it('updates the user password', async flags => {
// cleanup
flags.onCleanup = function() {
Auth.decodeToken.restore();
UserService.findById.restore();
UserService.update.restore();
};
// setup
const fakePass = 'new-password';
const user = { id: 1, username: 'admin', email: 'admin@gmail.com', active: true };
Sinon.stub(Auth, 'decodeToken')
.withArgs(token, Auth.token.PASSWORD_RESET)
.resolves({ id: user.id });
Sinon.stub(UserService, 'findById')
.withArgs(user.id)
.resolves(user);
Sinon.stub(UserService, 'update')
.withArgs(user.id, { email: user.email, password: fakePass })
.resolves();
// exercise
const response = await server.inject({
method: 'POST',
url: `/password-update?token=${token}`,
payload: {
password: fakePass,
email: user.email
}
});
// validate
expect(Auth.decodeToken.calledOnce).to.be.true();
expect(UserService.findById.calledOnce).to.be.true();
expect(UserService.update.calledOnce).to.be.true();
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
expect(response.result.success).to.be.true();
expect(response.result.message).to.equals('password update');
});
it('does not update the user password when token verification fails', async flags => {
// cleanup
flags.onCleanup = function() {
Auth.decodeToken.restore();
};
// setup
Sinon.stub(Auth, 'decodeToken').rejects();
// exercise
const response = await server.inject({
method: 'POST',
url: `/password-update?token=${token}`
});
// validate
expect(Auth.decodeToken.calledOnce).to.be.true();
expect(response.statusCode).to.equal(403);
expect(response.statusMessage).to.equal('Forbidden');
expect(response.result.message).to.equal('Authentication Failure');
});
it('does not update the user password when user is not found', async flags => {
// cleanup
flags.onCleanup = function() {
Auth.decodeToken.restore();
UserService.findById.restore();
};
// setup
Sinon.stub(Auth, 'decodeToken').resolves({ id: 1 });
Sinon.stub(UserService, 'findById').rejects();
// exercise
const response = await server.inject({
method: 'POST',
url: `/password-update?token=${token}`
});
// validate
expect(Auth.decodeToken.calledOnce).to.be.true();
expect(UserService.findById.calledOnce).to.be.true();
expect(response.statusCode).to.equal(403);
expect(response.statusMessage).to.equal('Forbidden');
expect(response.result.message).to.equal('Authentication Failure');
});
it('does not update the user password when user is not active', async flags => {
// cleanup
flags.onCleanup = function() {
Auth.decodeToken.restore();
UserService.findById.restore();
};
// setup
const user = { id: 1, username: 'admin', email: 'admin@gmail.com', active: false };
Sinon.stub(Auth, 'decodeToken').resolves({ id: user.id });
Sinon.stub(UserService, 'findById').resolves(user);
// exercise
const response = await server.inject({
method: 'POST',
url: `/password-update?token=${token}`
});
// validate
expect(Auth.decodeToken.calledOnce).to.be.true();
expect(UserService.findById.calledOnce).to.be.true();
expect(response.statusCode).to.equal(403);
expect(response.statusMessage).to.equal('Forbidden');
expect(response.result.message).to.equal(NSError.AUTH_UNAUTHORIZED().message);
});
it('does not update the user password if email is incorrect', async flags => {
// cleanup
flags.onCleanup = function() {
Auth.decodeToken.restore();
UserService.findById.restore();
};
// setup
const user = { id: 1, username: 'admin', email: 'admin@gmail.com', active: true };
Sinon.stub(Auth, 'decodeToken').resolves({ id: user.id });
Sinon.stub(UserService, 'findById').resolves(user);
// exercise
const response = await server.inject({
method: 'POST',
url: `/password-update?token=${token}`,
payload: {
password: 'password',
email: 'invalid'
}
});
// validate
expect(Auth.decodeToken.calledOnce).to.be.true();
expect(UserService.findById.calledOnce).to.be.true();
expect(response.statusCode).to.equal(403);
expect(response.statusMessage).to.equal('Forbidden');
expect(response.result.message).to.equal(NSError.AUTH_UNAUTHORIZED().message);
});
it('handles update password errors', async flags => {
// cleanup
flags.onCleanup = function() {
Auth.decodeToken.restore();
UserService.findById.restore();
UserService.update.restore();
};
// setup
const user = { id: 1, username: 'admin', email: 'admin@gmail.com', active: true };
Sinon.stub(Auth, 'decodeToken').resolves({ id: user.id });
Sinon.stub(UserService, 'findById').resolves(user);
Sinon.stub(UserService, 'update').rejects();
// exercise
const response = await server.inject({
method: 'POST',
url: `/password-update?token=${token}`,
payload: {
password: 'password',
email: user.email
}
});
// validate
expect(Auth.decodeToken.calledOnce).to.be.true();
expect(UserService.findById.calledOnce).to.be.true();
expect(UserService.update.calledOnce).to.be.true();
expect(response.statusCode).to.equal(500);
expect(response.statusMessage).to.equal('Internal Server Error');
expect(response.result.message).to.equal('An internal server error occurred');
});
});
| academia-de-codigo/noire-server | test/modules/authorization/controllers/login.js | JavaScript | mit | 17,913 |
require('./helpers/browserification').remove();
require('./helpers/readme').restore();
| addyosmani/node-jscs | publish/postpublish.js | JavaScript | mit | 87 |
var file_8h =
[
[ "FileInfo", "classargcv_1_1io_1_1_file_info.html", "classargcv_1_1io_1_1_file_info" ],
[ "File", "classargcv_1_1io_1_1_file.html", "classargcv_1_1io_1_1_file" ],
[ "FileMode", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9", [
[ "kModeDir", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a44557345a7e9ea874e764c35931447f2", null ],
[ "kModeAppend", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9aea38a73578409d18ad40dc9cb9d349ce", null ],
[ "kModeExclusive", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9ad748eeebf972431b4b484652c61297e6", null ],
[ "kModeTemporary", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a2953078c5581bda53580eb346d3e63e1", null ],
[ "kModeSymlink", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9acf262e2a15d2b4f53e19782e61e17ae7", null ],
[ "kModeDevice", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a4341e42c350023742b119ab955636fb6", null ],
[ "kModeNamedPipe", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a33a9ca6e22e5efd22be10e48996a5ea9", null ],
[ "kModeSocket", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9addf541900ce4fc537842eae35dbfd3fe", null ],
[ "kModeSetuid", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a8757f6f7bda76189a384e384b1bd6947", null ],
[ "kModeSetgid", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9aa49f0b8317189b24c943b220890096b7", null ],
[ "kModeCharDevice", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a7647e27e962c7614225d9bd03d2fad94", null ],
[ "kModeSticky", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9acd782ae4b63d6c0cec47e98739922d7b", null ],
[ "kModeIrregular", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a9c43ae12407c7f4b7f098a0ad517ae90", null ],
[ "kModeType", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9a90b53e451b28a4a6214bfee9000fbd70", null ],
[ "kModePerm", "file_8h.html#a13c6afd603d5cfc59aa2aee504b9e7a9aeb91ed7686b938a330711f28610ea661", null ]
] ]
]; | yuikns/argcv | docs/html/file_8h.js | JavaScript | mit | 1,987 |
app.models.PageableUsers = Backbone.PageableCollection.extend({
model: app.models.User,
url: app.API_ROOT + "/user",
initialize: function (models, options) {
if (options) {
this.userId = options.userId;
this.action = options.action;
}
},
state: {
pageSize: 50,
sortKey: "createdDate",
order: 1
},
queryParams: {
sortKey: "sort",
currentPage: "current",
pageSize: "limit",
totalPages: "pageCount"
},
parseState: function (resp, queryParams, state, options) {
return { totalRecords: resp.rowCount };
},
parseRecords: function (resp, options) {
return resp.rows;
}
});
| sphildreth/roadie | roadie/Content/js/models/userModels.js | JavaScript | mit | 733 |
// Flags: --expose-http2
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const http2 = require('http2');
const assert = require('assert');
const {
NGHTTP2_INTERNAL_ERROR
} = http2.constants;
const errorCheck = common.expectsError({
code: 'ERR_HTTP2_STREAM_ERROR',
type: Error,
message: `Stream closed with error code ${NGHTTP2_INTERNAL_ERROR}`
}, 2);
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respondWithFD(common.firstInvalidFD());
stream.on('error', common.mustCall(errorCheck));
});
server.listen(0, () => {
const client = http2.connect(`http://localhost:${server.address().port}`);
const req = client.request();
req.on('response', common.mustCall());
req.on('error', common.mustCall(errorCheck));
req.on('data', common.mustNotCall());
req.on('end', common.mustCall(() => {
assert.strictEqual(req.rstCode, NGHTTP2_INTERNAL_ERROR);
client.destroy();
server.close();
}));
req.end();
});
| hoho/dosido | nodejs/test/parallel/test-http2-respond-file-fd-invalid.js | JavaScript | mit | 1,029 |
import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._nsps = Object.create(null);
this._sockets = this.of("/");
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
| Ragg-/maya.js | mayajs/__src-server/socket.io-wrapper/server/server.js | JavaScript | mit | 1,166 |
export default {
en: {
name: "English",
dir: "ltr",
assessment: {
unansweredQuestionWarning: "Warning There are unanswered questions", // Warning displayed on last question if there are unanswered questions
leavingQuizPopup: "Don’t leave!", // Text displayed on javascript window alert when a student navigates away from summative quiz
counterQuestion: "Question {0} of {1}", // Counter for when only a single question is displayed at a time
counterPage: "Page {0} of {1}" // Counter for when many questions are displayed at a time
},
remaining: {
one_left: "Answer 1 more question.",
many_left: "Answer {0} more questions.",
done: "Well done!"
},
assessmentComplete: {
complete: "Thank you" // Text displayed when quiz is completed
},
twoButtonNav:{
previousButton: "Previous", // Text displayed on previous questions button
nextButton: "Next", // Text displayed on next questions button
checkAnswerButton: "Check Answer", // Text displayed on next questions button,
saveFileButton: "Save File", // Text displayed on save file button
saveAnswerButton: "Save Answer", // Text displayed on save answer button
submitButton: "Finish" // Text displayed on submit button
},
retriesExceeded: {
triesExceeded: "Too many tries" // Text displayed when a student has run out of quiz attempts
},
start: {
summativeInstruction: "Summative Quiz", // Instructions for summative quiz
formativeInstruction: "Formative Quiz", // Instructions for formative quiz
showWhatYouKnowInstruction: "Show What You Know", // Instructions for 'show what you know' style quiz
startButton: "Start Quiz" // Text displayed on start quiz button
},
notFound: {
notFound: "Not Found" // Text displayed when a page is not found
},
about: {
title:"Open Assessments" // About page title
},
loading: {
loading: "Loading..."
},
audioUpload: {
record: "Record",
stop: "Stop"
},
fileUpload: {
chooseFile: "Choose a File to Upload"
},
middleware: {
// Text displayed when a user tries to check an answer without
// selecting one first (Applies to questions that presents discrete number
// of choices for the user to choose from).
mustSelectAnswer: "Please select a valid answer",
// Text displayed when a user tries to check an answer without
// selecting one first (Applies when the question expects user input in a
// text box).
mustEnterAnswer: "Please enter a valid answer",
// Text displayed when a user tries to check an answer without
// selecting one first (Applies when the question expects user to upload
// a file).
mustUploadFile: "Please upload a file",
// Text displayed when a user tries to check an answer without
// selecting one first (Applies when the question expects user use the audio
// recorder to record an audio sample).
mustRecordFile: "Please record an audio sample"
}
}
};
| atomicjolt/open_assessments | client/js/_player/locales/en.js | JavaScript | mit | 3,118 |
export { default } from "ember-bscomponents/components/bs-pill/component";
| patricklx/ember-bscomponents | app/components/bs/pill/component.js | JavaScript | mit | 75 |
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
"_widgetLabel": "Analiza troškova",
"unableToFetchInfoErrMessage": "Nije moguće pribavljanje servisa geometrije/detalja konfigurisanog sloja",
"invalidCostingGeometryLayer": "Pribavljanje 'esriFieldTypeGlobalID' u sloju troškova geometrije nije moguće.",
"projectLayerNotFound": "Pronalaženje sloja konfigurisanog projekta u mapi nije moguće.",
"costingGeometryLayerNotFound": "Pronalaženje sloja konfigurisane geometrije troškova u mapi nije moguće.",
"projectMultiplierTableNotFound": "Pronalaženje konfigurisane tabele dodatnih troškova multiplikatora projekta u mapi nije moguće.",
"projectAssetTableNotFound": "Pronalaženje konfigurisane tabele resursa projekta u mapi nije moguće.",
"createLoadProject": {
"createProjectPaneTitle": "Kreiraj projekat",
"loadProjectPaneTitle": "Učitaj projekat",
"projectNamePlaceHolder": "Naziv projekta",
"projectDescPlaceHolder": "Opis projekta",
"selectProject": "Izaberi projekat",
"viewInMapLabel": "Prikaži na mapi",
"loadLabel": "Učitaj",
"createLabel": "Kreiraj",
"deleteProjectConfirmationMsg": "Želite li zaista da obrišete projekat?",
"noAssetsToViewOnMap": "Izabrani projekat nema nijedan resurs za prikaz na mapi.",
"projectDeletedMsg": "Projekat je uspešno obrisan.",
"errorInCreatingProject": "Greška u kreiranju projekta.",
"errorProjectNotFound": "Projekat nije pronađen.",
"errorInLoadingProject": "Proverite da li je važeći projekat izabran.",
"errorProjectNotSelected": "Izaberite projekat sa padajuće liste",
"errorDuplicateProjectName": "Naziv projekta već postoji.",
"errorFetchingPointLabel": "Greška prilikom dobavljanja tačke oznake. Pokušajte ponovo",
"errorAddingPointLabel": "Greška prilikom dodavanja tačke oznake. Pokušajte ponovo"
},
"statisticsSettings": {
"tabTitle": "Postavke statistike",
"addStatisticsLabel": "Dodaj statistiku",
"addNewStatisticsText": "Dodaj novu statistiku",
"deleteStatisticsText": "Obriši statistiku",
"moveStatisticsUpText": "Pomeri statistiku na gore",
"moveStatisticsDownText": "Pomeri statistiku na dole",
"layerNameTitle": "Sloj",
"statisticsTypeTitle": "Tip",
"fieldNameTitle": "Polje",
"statisticsTitle": "Oznaka",
"actionLabelTitle": "Radnje",
"selectDeselectAllTitle": "Selektuj sve",
"layerCheckbox": "Okvir za potvrdu za raspored"
},
"statisticsType": {
"countLabel": "Brojač",
"averageLabel": "Prosečno",
"maxLabel": "Maksimum",
"minLabel": "Minimum",
"summationLabel": "Zbir",
"areaLabel": "Površina",
"lengthLabel": "Dužina"
},
"costingInfo": {
"noEditableLayersAvailable": "Sloj(evi) treba da bude(-u) označen(i) kao urediv(i) u kartici postavki sloja"
},
"workBench": {
"refresh": "Osveži",
"noAssetAddedMsg": "Nema dodatih resursa",
"units": "jedinica(e)",
"assetDetailsTitle": "Detalji resursa stavke",
"costEquationTitle": "Jednačina troškova",
"newCostEquationTitle": "Nova jednačina",
"defaultCostEquationTitle": "Podrazumevana jednačina",
"geographyTitle": "Geografija",
"scenarioTitle": "Scenario",
"costingInfoHintText": "<div>Savet: koristite sledeće ključne reči</div><ul><li><b>{TOTALCOUNT}</b>: koristi ukupan broj istog tipa resursa u geografiji</li> <li><b>{MEASURE}</b>: Koristi dužinu za resurs linije i oblast za resurs poligona</li><li><b>{TOTALMEASURE}</b>: Koristi ukupnu dužinu za resurs linije i ukupnu oblast za resurs poligona za isti tip u geografiji</li></ul> Možete da koristite funkcije kao što su:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Izmenite jednačinu troškova prema zahtevima vašeg projekta.",
"zoomToAsset": "Zumiraj na resurs",
"deleteAsset": "Obriši resurs",
"closeDialog": "Zatvori dijalog",
"objectIdColTitle": "ID objekta",
"costColTitle": "Trošak",
"errorInvalidCostEquation": "Nevažeća jednačina troška.",
"errorInSavingAssetDetails": "Čuvanje detalja resursa nije moguće.",
"featureModeText": "Režim geoobjekata",
"sketchToolTitle": "Skiciraj",
"selectToolTitle": "Selektujte",
"downloadCSVBtnTitle": "Izvezi izveštaj"
},
"assetDetails": {
"inGeography": " u${geography} ",
"withScenario": " sa ${scenario}",
"totalCostTitle": "Ukupan trošak",
"additionalCostLabel": "Opis",
"additionalCostValue": "Vrednost",
"additionalCostNetValue": "Neto vrednost"
},
"projectOverview": {
"assetItemsTitle": "Stavke resursa",
"assetStatisticsTitle": "Statistika resursa",
"projectSummaryTitle": "Rezime projekta",
"projectName": "Naziv projekta: ${name}",
"totalCostLabel": "Ukupan trošak projekta (*):",
"grossCostLabel": "Bruto trošak projekta (*):",
"roundingLabel": "* Zaokruživanje na '${selectedRoundingOption}'",
"unableToSaveProjectBoundary": "Čuvanje granica projekta u sloju projekta nije moguće.",
"unableToSaveProjectCost": "Čuvanje trošk(ov)a projekta u sloju projekta nije moguće.",
"roundCostValues": {
"twoDecimalPoint": "Dve decimale",
"nearestWholeNumber": "Najbliži ceo broj",
"nearestTen": "Najbliža desetica",
"nearestHundred": "Najbliža stotina",
"nearestThousand": "Najbliža hiljada",
"nearestTenThousands": "Najbliža desetina hiljada"
}
},
"projectAttribute": {
"projectAttributeText": "Atribut projekta",
"projectAttributeTitle": "Izmeni atribute projekta"
},
"costEscalation": {
"costEscalationLabel": "Dodaj dodatne troškove",
"valueHeader": "Vrednost",
"addCostEscalationText": "Dodaj dodatni trošak",
"deleteCostEscalationText": "Obriši selektovani dodatni trošak",
"moveCostEscalationUpText": "Pomeri selektovani dodatni trošak na gore",
"moveCostEscalationDownText": "Pomeri selektovani dodatni trošak na dole",
"invalidEntry": "Jedan ili više unosa je nevažeće.",
"errorInSavingCostEscalation": "Čuvanje detalja dodatnog troška nije moguće."
},
"scenarioSelection": {
"popupTitle": "Izaberite scenario za resurs",
"regionLabel": "Geografija",
"scenarioLabel": "Scenario",
"noneText": "Ništa",
"copyFeatureMsg": "Želite li da kopirate izabrane geoobjekte?"
},
"detailStatistics": {
"detailStatisticsLabel": "Statistika detalja",
"noDetailStatisticAvailable": "Nema dodate statistike resursa"
},
"copyFeatures": {
"title": "Kopiraj geoobjekte",
"createFeatures": "Kreiraj geoobjekte",
"createSingleFeature": "Kreiraj 1 geoobjekat višedelne geometrije",
"noFeaturesSelectedMessage": "Nijedan geoobjekat nije izabran",
"selectFeatureToCopyMessage": "Izaberite geoobjekte za kopiranje."
},
"updateCostEquationPanel": {
"updateProjectCostTabLabel": "Ažuriraj jednačine projekta",
"updateProjectCostSelectProjectTitle": "Selektuj sve projekte",
"updateButtonTextForm": "Ažuriraj",
"updateProjectCostSuccess": "Jednačine troška selektovanih projekata su ažurirane",
"updateProjectCostError": "Ažuriranje jednačine troška selektovanih projekata nije moguće",
"updateProjectNoProject": "Nije pronađen nijedan projekat"
}
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/CostAnalysis/nls/sr/strings.js | JavaScript | mit | 8,005 |
angular.module('portal')
.factory('Search', ['$resource', 'BaseUrl', function ($resource, BaseUrl) {
var services = {},
_search = $resource(BaseUrl + 'search/general/', {}, {
get: {method: 'GET'}
});
services.general = function (query, success) {
return _search.get({q: query}, success);
};
return services;
}]);
| Axiologue/MindfulClick | src/js/angular/services/landingServices.js | JavaScript | mit | 347 |
'use strict';
module.exports = require('./EmbedXMLConverter');
| abhaga/substance | packages/embed/EmbedXMLConverter.js | JavaScript | mit | 64 |
/**
* @fileoverview Event stream backed by the events API
* @author mwiller
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
var Readable = require('stream').Readable,
qs = require('querystring'),
util = require('util');
// ------------------------------------------------------------------------------
// Private
// ------------------------------------------------------------------------------
/** @const {int} The number of ms to wait before retrying after an error */
var RETRY_DELAY = 1000;
/** @const {int} Max number of IDs to track for deduplication before cleaning */
var MAX_DEDUP_SIZE = 5000;
// ------------------------------------------------------------------------------
// Public
// ------------------------------------------------------------------------------
/**
* Stream of Box events from a given client and point in time
* @param {BoxClient} client The client to use to get events
* @param {string} streamPosition The point in time to start at
* @constructor
*/
function EventStream(client, streamPosition) {
Readable.call(this, {
objectMode: true
});
/** @var {BoxClient} The client for making API calls */
this._client = client;
/** @var {string} The latest stream position */
this._streamPosition = streamPosition;
/** @var {?Object} The information for how to long poll */
this._longPollInfo = null;
/** @var {int} The number of long poll requests we've made against one URL so far */
this._longPollRetries = 0;
/** @var {Object.<string, boolean>} Hash of event IDs we've already pushed */
this._dedupHash = {};
}
util.inherits(EventStream, Readable);
/**
* Retrieve the url and params for long polling for new updates
* @returns {void}
*/
EventStream.prototype.getLongPollInfo = function() {
var self = this;
this._client.events.getLongPollInfo(function(err, longPollInfo) {
if (err) {
self.emit('error', err);
setTimeout(function() {
self.getLongPollInfo();
}, RETRY_DELAY);
return;
}
// On getting new long poll info, reset everything
self._longPollInfo = longPollInfo;
self._longPollRetries = 0;
self.doLongPoll();
});
};
/**
* Long poll for notification of new events. We do this rather than
* polling for the events directly in order to minimize the number of API
* calls necessary.
* @returns {void}
*/
EventStream.prototype.doLongPoll = function() {
var self = this;
// If we're over the max number of retries, reset
if (this._longPollRetries > this._longPollInfo.max_retries) {
this.getLongPollInfo();
return;
}
var url = this._longPollInfo.url,
qsDelim = url.indexOf('?'),
query = {};
// Break out the query params, otherwise the request URL gets messed up
if (qsDelim > 0) {
query = qs.parse(url.substr(qsDelim + 1));
url = url.substr(0, qsDelim);
}
query.stream_position = this._streamPosition;
var options = {
qs: query,
timeout: this._longPollInfo.retry_timeout * 1000
};
this._longPollRetries += 1;
this._client.get(url, options, this._client.defaultResponseHandler(function(err, data) {
if (err) {
setTimeout(function() {
self.getLongPollInfo();
}, RETRY_DELAY);
return;
}
if (data.message === 'reconnect') {
self.getLongPollInfo();
return;
}
// We don't expect any messages other than reconnect and new_change, so if
// we get one just retry the long poll
if (data.message !== 'new_change') {
self.doLongPoll();
return;
}
self.fetchEvents();
}));
};
/**
* Fetch the latest group of events and push them into the stream
* @returns {void}
*/
EventStream.prototype.fetchEvents = function() {
var self = this,
eventParams = {
stream_position: this._streamPosition
};
this._client.events.get(eventParams, function(err, events) {
if (err) {
self.emit('error', err);
setTimeout(function() {
self.getLongPollInfo();
}, RETRY_DELAY);
return;
}
// If the response wasn't what we expected, re-poll
if (!events.entries || !events.next_stream_position) {
self.doLongPoll();
return;
}
self._streamPosition = events.next_stream_position;
// De-duplicate the fetched events, since the API often returns
// the same events at multiple subsequent stream positions
var newEvents = events.entries.filter(function(event) {
return !self._dedupHash[event.event_id];
});
// If there aren't any non-duplicate events, go back to polling
if (!newEvents.length) {
self.doLongPoll();
return;
}
// Push new events into the stream
newEvents.forEach(function(event) {
self._dedupHash[event.event_id] = true;
self.push(event);
});
// Once the deduplication filter gets too big, clean it up
if (Object.keys(self._dedupHash).length >= MAX_DEDUP_SIZE) {
self.cleanupDedupFilter(events.entries);
}
});
};
/**
* Clean up the deduplication filter, to prevent it from growing
* too big and eating up memory. We look at the latest set of events
* returned and assume that any IDs not in that set don't need to be
* tracked for deduplication any more.
* @param {Object[]} latestEvents The latest events from the API
* @returns {void}
*/
EventStream.prototype.cleanupDedupFilter = function(latestEvents) {
var self = this,
dedupIDs = Object.keys(this._dedupHash);
dedupIDs.forEach(function(eventID) {
var isEventCleared = !latestEvents.find(function(e) {
return e.event_id === eventID;
});
if (isEventCleared) {
delete self._dedupHash[eventID];
}
});
};
/**
* Implementation of the stream-internal read function. This is called
* by the stream whenever it needs more data, and will not be called again
* until data is pushed into the stream.
* @returns {void}
*/
EventStream.prototype._read = function() {
// Start the process of getting new events
this.getLongPollInfo();
};
module.exports = EventStream;
| kmcroft13/box-templates | node_modules/box-node-sdk/lib/event-stream.js | JavaScript | mit | 5,963 |
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('localStorageWrapper', ['module', 'exports', '../utils/isLocalStorageValid', '../utils/serializer', '../utils/promise', '../utils/executeCallback', '../utils/normalizeKey', '../utils/getCallback'], factory);
} else if (typeof exports !== "undefined") {
factory(module, exports, require('../utils/isLocalStorageValid'), require('../utils/serializer'), require('../utils/promise'), require('../utils/executeCallback'), require('../utils/normalizeKey'), require('../utils/getCallback'));
} else {
var mod = {
exports: {}
};
factory(mod, mod.exports, global.isLocalStorageValid, global.serializer, global.promise, global.executeCallback, global.normalizeKey, global.getCallback);
global.localStorageWrapper = mod.exports;
}
})(this, function (module, exports, _isLocalStorageValid, _serializer, _promise, _executeCallback, _normalizeKey, _getCallback) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isLocalStorageValid2 = _interopRequireDefault(_isLocalStorageValid);
var _serializer2 = _interopRequireDefault(_serializer);
var _promise2 = _interopRequireDefault(_promise);
var _executeCallback2 = _interopRequireDefault(_executeCallback);
var _normalizeKey2 = _interopRequireDefault(_normalizeKey);
var _getCallback2 = _interopRequireDefault(_getCallback);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return _promise2.default.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = _serializer2.default;
return _promise2.default.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
key = (0, _normalizeKey2.default)(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
key = (0, _normalizeKey2.default)(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
key = (0, _normalizeKey2.default)(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new _promise2.default(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
(0, _executeCallback2.default)(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = _getCallback2.default.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = _promise2.default.reject('Invalid arguments');
} else {
promise = new _promise2.default(function (resolve) {
if (!options.storeName) {
resolve(options.name + '/');
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
(0, _executeCallback2.default)(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
_support: (0, _isLocalStorageValid2.default)(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys,
dropInstance: dropInstance
};
exports.default = localStorageWrapper;
module.exports = exports['default'];
});
| freestone-lab/TSLibrary | TSBrowser/node_modules/localforage/build/es5src/drivers/localstorage.js | JavaScript | mit | 12,385 |
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("../npmci.plugins"));
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kLnBsdWdpbnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9tb2RfY2xlYW4vbW9kLnBsdWdpbnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxzQ0FBaUMifQ== | pushrocks/npmci | dist/mod_clean/mod.plugins.js | JavaScript | mit | 455 |
/* */
var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
var objectProto = Object.prototype;
var objToString = objectProto.toString;
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
| nayashooter/ES6_React-Bootstrap | public/jspm_packages/npm/lodash-compat@3.10.2/lang/isTypedArray.js | JavaScript | mit | 1,875 |
var _ = require('underscore');
var u = require('../Utils');
var DownloadWriter = require('./DownloadWriterAsyncTask');
var BodyRequest = require('./BodyRequestAsyncTask');
var MetaDataBuilder = require('./MetaDataBuilderSyncTask');
var DownloadTimeout = require('./DownloadTimeoutTask');
var ThreadUpdator = require('./ThreadUpdateTask');
var ThreadsDestroyer = require('./ThreadsDestroyer');
var ExecutorGenerator = function(fd, threads, fileSize, url, method, port, headers, cParams) {
this.fd = fd;
this.threads = threads;
this.fileSize = fileSize;
this.url = url;
this.method = method;
this.port = port;
this.headers = headers;
this.cParams = cParams || {};
};
ExecutorGenerator.prototype.execute = function(callback) {
var executor = {};
var self = this;
executor.threadsDestroyer = u.executor(ThreadsDestroyer, this.threads);
executor.threadUpdator = u.executor(ThreadUpdator);
executor.writer = u.executor(DownloadWriter, self.fd);
executor.timer = u.executor(DownloadTimeout, self.threads, self.cParams);
executor.metaBuilder = u.executor(MetaDataBuilder, self.threads, self.fileSize, self.url, self.method, self.port, self.headers, self.cParams);
_.each(self.threads, function(item) {
item.bodyRequest = u.executor(BodyRequest, self.url, item.position, item.end, self.cParams);
});
executor.threads = this.threads;
callback(null, executor);
};
module.exports = ExecutorGenerator; | nicolsondsouza/Multi-threaded-downloader | lib/core/ExecutorGenerator.js | JavaScript | mit | 1,415 |
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ImageNavigateNext = React.createClass({
displayName: 'ImageNavigateNext',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z' })
);
}
});
module.exports = ImageNavigateNext; | checkraiser/material-ui2 | lib/svg-icons/image/navigate-next.js | JavaScript | mit | 406 |
import React from 'react';
import ReactDOM from 'react-dom';
import App from './jsx/App.jsx';
ReactDOM.render(<App />, document.getElementById('app')) | mqy1023/react-with-es6 | 02、jsx/src/main.js | JavaScript | mit | 151 |
var text = '{"Title":"Shark Stories","Date":"15 December 2015- 18th December 2015","phone":"555 1234567"}'
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.Title + "<br>" +
obj.Date + "<br>" +
obj.phone; | rodneywardle/finalmuseumapp | json.js | JavaScript | mit | 244 |
/**
* Module dependencies.
*/
var utils = require('../utils');
/**
* Expose `invoke()` function on requests.
*
* Once `invoke()` is exposed on a request, it can be called in order to invoke
* a specific controller and action in a Locomotive appliction. This is
* typically done to call into a Locmotive application from middleware or routes
* that exist outside of the application itself.
*
* If a request is being processed from within a controller, it is recommended
* to use `this.invoke()` on the controller, rather than `req.invoke()`.
*
* Examples:
*
* this.express.get(/regex/, function(req, res, next) {
* req.invoke('foo', 'bar', next);
* });
*
* this.express.get(/regex/, function(req, res, next) {
* req.invoke('foo#bar', next);
* });
*
* @return {Function}
* @api protected
*/
module.exports = function(options) {
options = options || {};
var name = options.name || 'invoke';
return function(req, res, next) {
// This middleware is bound with a `this` context of a Locmotive app.
var app = this;
req[name] = function(controller, action, next) {
if (typeof action == 'function') {
next = action;
action = undefined;
}
if (!action) {
var split = controller.split('#');
if (split.length > 1) {
// shorthand controller#action form
controller = split[0];
action = split[1];
}
}
controller = utils.controllerize(controller);
action = utils.actionize(action);
next = next || function(err) {
if (err) { throw err; }
};
// Get the middleware that the Locomotive router uses to handle requests,
// binding it to a controller and action.
var handle = app._routes._handle(controller, action).bind(app);
// Forward the current request into Locomotive to be handled by a
// controller and action.
handle(req, res, next);
};
next();
}
}
| laugga/memories.laugga.com | src/node_modules/locomotive/lib/locomotive/middleware/invoke.js | JavaScript | mit | 1,991 |
/*! RowsGroup for DataTables v1.0.0
* 2015 Alexey Shildyakov ashl1future@gmail.com
*/
/**
* @summary RowsGroup
* @description Group rows by specified columns
* @version 1.0.0
* @file dataTables.rowsGroup.js
* @author Alexey Shildyakov (ashl1future@gmail.com)
* @contact ashl1future@gmail.com
* @copyright Alexey Shildyakov
*
* License MIT - http://datatables.net/license/mit
*
* This feature plug-in for DataTables automatically merges columns cells
* based on it's values equality. It supports multi-column row grouping
* in according to the requested order with dependency from each previous
* requested columns. Now it supports ordering and searching.
* Please see the example.html for details.
*
* Rows grouping in DataTables can be enabled by using any one of the following
* options:
*
* * Setting the `rowsGroup` parameter in the DataTables initialisation
* to array which containes columns selectors
* (https://datatables.net/reference/type/column-selector) used for grouping. i.e.
* rowsGroup = [1, 'columnName:name', ]
* * Setting the `rowsGroup` parameter in the DataTables defaults
* (thus causing all tables to have this feature) - i.e.
* `$.fn.dataTable.defaults.RowsGroup = [0]`.
* * Creating a new instance: `new $.fn.dataTable.RowsGroup( table, columnsForGrouping );`
* where `table` is a DataTable's API instance and `columnsForGrouping` is the array
* described above.
*
* For more detailed information please see:
*
*/
(function($){
ShowedDataSelectorModifier = {
order: 'current',
page: 'current',
search: 'applied',
}
GroupedColumnsOrderDir = 'asc';
/*
* columnsForGrouping: array of DTAPI:cell-selector for columns for which rows grouping is applied
*/
var RowsGroup = function ( dt, columnsForGrouping )
{
this.table = dt.table();
this.columnsForGrouping = columnsForGrouping;
// set to True when new reorder is applied by RowsGroup to prevent order() looping
this.orderOverrideNow = false;
this.order = []
self = this;
$(document).on('order.dt', function ( e, settings) {
if (!self.orderOverrideNow) {
self._updateOrderAndDraw()
}
self.orderOverrideNow = false;
})
$(document).on('draw.dt', function ( e, settings) {
self._mergeCells()
})
this._updateOrderAndDraw();
};
RowsGroup.prototype = {
_getOrderWithGroupColumns: function (order, groupedColumnsOrderDir)
{
if (groupedColumnsOrderDir === undefined)
groupedColumnsOrderDir = GroupedColumnsOrderDir
var self = this;
var groupedColumnsIndexes = this.columnsForGrouping.map(function(columnSelector){
return self.table.column(columnSelector).index()
})
var groupedColumnsKnownOrder = order.filter(function(columnOrder){
return groupedColumnsIndexes.indexOf(columnOrder[0]) >= 0
})
var nongroupedColumnsOrder = order.filter(function(columnOrder){
return groupedColumnsIndexes.indexOf(columnOrder[0]) < 0
})
var groupedColumnsKnownOrderIndexes = groupedColumnsKnownOrder.map(function(columnOrder){
return columnOrder[0]
})
var groupedColumnsOrder = groupedColumnsIndexes.map(function(iColumn){
var iInOrderIndexes = groupedColumnsKnownOrderIndexes.indexOf(iColumn)
if (iInOrderIndexes >= 0)
return [iColumn, groupedColumnsKnownOrder[iInOrderIndexes][1]]
else
return [iColumn, groupedColumnsOrderDir]
})
groupedColumnsOrder.push.apply(groupedColumnsOrder, nongroupedColumnsOrder)
return groupedColumnsOrder;
},
// Workaround: the DT reset ordering to 'asc' from multi-ordering if user order on one column (without shift)
// but because we always has multi-ordering due to grouped rows this happens every time
_getInjectedMonoSelectWorkaround: function(order)
{
if (order.length === 1) {
// got mono order - workaround here
var orderingColumn = order[0][0]
var previousOrder = this.order.map(function(val){
return val[0]
})
var iColumn = previousOrder.indexOf(orderingColumn);
if (iColumn >= 0) {
// assume change the direction, because we already has that in previos order
return [[orderingColumn, this._toogleDirection(this.order[iColumn][1])]]
} // else This is the new ordering column. Proceed as is.
} // else got milti order - work normal
return order;
},
_mergeCells: function()
{
var columnsIndexes = this.table.columns(this.columnsForGrouping, ShowedDataSelectorModifier).indexes().toArray()
var showedRowsCount = this.table.rows(ShowedDataSelectorModifier)[0].length
this._mergeColumn(0, showedRowsCount - 1, columnsIndexes)
},
// the index is relative to the showed data
// (selector-modifier = {order: 'current', page: 'current', search: 'applied'}) index
_mergeColumn: function(iStartRow, iFinishRow, columnsIndexes)
{
var columnsIndexesCopy = columnsIndexes.slice()
currentColumn = columnsIndexesCopy.shift()
currentColumn = this.table.column(currentColumn, ShowedDataSelectorModifier)
var columnNodes = currentColumn.nodes()
var columnValues = currentColumn.data()
var newSequenceRow = iStartRow,
iRow;
for (iRow = iStartRow + 1; iRow <= iFinishRow; ++iRow) {
if (columnValues[iRow] === columnValues[newSequenceRow]) {
$(columnNodes[iRow]).hide()
} else {
$(columnNodes[newSequenceRow]).show()
$(columnNodes[newSequenceRow]).attr('rowspan', (iRow-1) - newSequenceRow + 1)
if (columnsIndexesCopy.length > 0)
this._mergeColumn(newSequenceRow, (iRow-1), columnsIndexesCopy)
newSequenceRow = iRow;
}
}
$(columnNodes[newSequenceRow]).show()
$(columnNodes[newSequenceRow]).attr('rowspan', (iRow-1)- newSequenceRow + 1)
if (columnsIndexesCopy.length > 0)
this._mergeColumn(newSequenceRow, (iRow-1), columnsIndexesCopy)
},
_toogleDirection: function(dir)
{
return dir == 'asc'? 'desc': 'asc';
},
_updateOrderAndDraw: function()
{
this.orderOverrideNow = true;
var currentOrder = this.table.order();
currentOrder = this._getInjectedMonoSelectWorkaround(currentOrder);
this.order = this._getOrderWithGroupColumns(currentOrder)
this.table.order($.extend(true, Array(), this.order))
this.table.draw()
},
};
$.fn.dataTable.RowsGroup = RowsGroup;
$.fn.DataTable.RowsGroup = RowsGroup;
// Automatic initialisation listener
$(document).on( 'init.dt', function ( e, settings ) {
if ( e.namespace !== 'dt' ) {
return;
}
var api = new $.fn.dataTable.Api( settings );
if ( settings.oInit.rowsGroup ||
$.fn.dataTable.defaults.rowsGroup )
{
options = settings.oInit.rowsGroup?
settings.oInit.rowsGroup:
$.fn.dataTable.defaults.rowsGroup;
new RowsGroup( api, options );
}
} );
}(jQuery));
/*
TODO: Provide function which determines the all <tr>s and <td>s with "rowspan" html-attribute is parent (groupped) for the specified <tr> or <td>. To use in selections, editing or hover styles.
TODO: Feature
Use saved order direction for grouped columns
Split the columns into grouped and ungrouped.
user = grouped+ungrouped
grouped = grouped
saved = grouped+ungrouped
For grouped uses following order: user -> saved (because 'saved' include 'grouped' after first initialisation). This should be done with saving order like for 'groupedColumns'
For ungrouped: uses only 'user' input ordering
*/
| primasalama/simonik | assets/js/dataTables.rowsGroup.js | JavaScript | mit | 7,276 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//-------- jQuery (1)
// require jquery
//= require jquery.min
//-------- jQuery Turbolinks
//= require jquery.turbolinks
//-------- jQuery (2)
//= require jquery_ujs
//= require jquery-ui
//-------- Turbolinks
//= require turbolinks
//-------- Bootstrap
// require bootstrap.min
//-------- underscore
// require underscore
//= require underscore/underscore-min
//-------- gmaps
// require gmaps/google
//-------- [All files]
//= require_tree .
const goldenRatio = 1.618 ; | osorubeki-fujita/tokyometro.herokuapp | app/assets/javascripts/application.js | JavaScript | mit | 1,066 |
/*!
* customize <https://github.com/nknapp/ride-over>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
/* global describe */
/* global it */
// /* global before */
// /* global xdescribe */
// /* global xit */
'use strict'
var chai = require('chai')
var expect = chai.expect
var chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
var overrider = require('../').overrider
var mergeWith = require('lodash.mergewith')
var deep = require('deep-aplus')(Promise)
describe('The custom overrider', function () {
it('should concatenate arrays', function () {
expect(mergeWith({ a: [1, 2] }, { a: [3, 4] }, overrider).a).to.deep.equal([1, 2, 3, 4])
})
it('should concatenate arrays within promises', function () {
expect(deep(mergeWith({ a: Promise.resolve([1, Promise.resolve(2)]) }, { a: [3, 4] }, overrider).a)).to.eventually.deep.equal([1, 2, 3, 4])
})
})
| nknapp/customize | test/merge-spec.js | JavaScript | mit | 924 |
/*!
* Connect - session - Cookie
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var merge = require('utils-merge')
, cookie = require('cookie');
/**
* Initialize a new `Cookie` with the given `options`.
*
* @param {IncomingMessage} req
* @param {Object} options
* @api private
*/
var Cookie = module.exports = function Cookie(options) {
this.path = '/';
this.maxAge = null;
this.httpOnly = true;
if (options) merge(this, options);
// (null origin undefined) == undefined will be true
this.originalMaxAge = undefined == this.originalMaxAge
? this.maxAge
: this.originalMaxAge;
};
/*!
* Prototype.
*/
Cookie.prototype = {
/**
* Set expires `date`.
*
* @param {Date} date
* @api public
*/
// 设置过期时间
set expires(date) {
this._expires = date;
this.originalMaxAge = this.maxAge;
},
/**
* Get expires `date`.
*
* @return {Date}
* @api public
*/
// 获取过期时间
get expires() {
return this._expires;
},
/**
* Set expires via max-age in `ms`.
*
* @param {Number} ms
* @api public
*/
set maxAge(ms) {
this.expires = 'number' == typeof ms
? new Date(Date.now() + ms)
: ms;
},
/**
* Get expires max-age in `ms`.
*
* @return {Number}
* @api public
*/
get maxAge() {
return this.expires instanceof Date
? this.expires.valueOf() - Date.now()
: this.expires;
},
/**
* Return cookie data object.
*
* @return {Object}
* @api private
*/
get data() {
return {
originalMaxAge: this.originalMaxAge
, expires: this._expires
, secure: this.secure
, httpOnly: this.httpOnly
, domain: this.domain
, path: this.path
}
},
/**
* Return a serialized cookie string.
*
* @return {String}
* @api public
*/
serialize: function(name, val){
return cookie.serialize(name, val, this.data);
},
/**
* Return JSON representation of this cookie.
*
* @return {Object}
* @api private
*/
toJSON: function(){
return this.data;
}
};
| tianyk/express-session-research | session/cookie.js | JavaScript | mit | 2,177 |
/* transcode a file into ogg vorbis */
var groove = require('../');
var fs = require('fs');
if (process.argv.length < 4) usage();
groove.setLogging(groove.LOG_INFO);
var playlist = groove.createPlaylist();
var encoder = groove.createEncoder();
encoder.formatShortName = "ogg";
encoder.codecShortName = "vorbis";
var outStream = fs.createWriteStream(process.argv[3]);
encoder.on('buffer', function() {
var buffer;
while (buffer = encoder.getBuffer()) {
if (buffer.buffer) {
outStream.write(buffer.buffer);
} else {
cleanup();
return;
}
}
});
encoder.attach(playlist, function(err) {
if (err) throw err;
groove.open(process.argv[2], function(err, file) {
if (err) throw err;
playlist.insert(file, null);
});
});
function cleanup() {
var file = playlist.items()[0].file;
playlist.clear();
file.close(function(err) {
if (err) throw err;
encoder.detach(function(err) {
if (err) throw err;
playlist.destroy();
});
});
}
function usage() {
console.error("Usage: node transcode.js inputfile outputfile");
process.exit(1);
}
| andrewrk/node-groove | example/transcode.js | JavaScript | mit | 1,112 |
var $confWindow = args.getParam(0);
var $content = $confWindow.window('content');
$confWindow.window('dialog', true).window('loading', true);
Webos.require('/usr/lib/webos/data.js', function() {
$confWindow.window('loading', false);
var tabs = $.w.tabs().appendTo($content);
//Server status
var $currentStatus = $.w.container();
tabs.tabs('tab', 'Status', $currentStatus);
var $currentStatusText = $.w.label().appendTo($currentStatus);
var $startServerBtn = $.w.button('Start server').click(function() {
startServer();
}).appendTo($currentStatus);
var $stopServerBtn = $.w.button('Stop server').click(function() {
stopServer();
}).appendTo($currentStatus);
var $restartServerBtn = $.w.button('Restart server').click(function() {
restartServer();
}).appendTo($currentStatus);
//Server config
var $config = $.w.container();
tabs.tabs('tab', 'Configuration', $config);
var $noConfig = $.w.label('Cannot change WebSocket server config: server not supported.').appendTo($config);
var $form = $.w.entryContainer().appendTo($config);
var controls = {
enabled: $.w.switchButton('Enable the WebSocket server'),
autoStart: $.w.switchButton('Start automatically the WebSocket server if not running'),
port: $.w.numberEntry('Server port: '),
protocol: $.w.selectButton('Protocol: ', { ws: 'ws (unsecure connection)', wss: 'wss (secure connection)' })
};
for (var controlName in controls) {
controls[controlName].appendTo($form);
}
var $btns = $.w.buttonContainer().appendTo($form);
var $applyBtn = $.w.button('Update config').click(function() {
updateConfig();
}).appendTo($btns);
//protocol
if (window.location.protocol != 'https:') {
controls.protocol.selectButton('option', 'disabled', true);
}
var displayServerControls = function(serverStatus) {
if (!serverStatus.supported || !serverStatus.enabled) {
$startServerBtn.hide();
$stopServerBtn.hide();
$restartServerBtn.hide();
} else if (serverStatus.started) {
$startServerBtn.hide();
$stopServerBtn.show();
$restartServerBtn.show();
} else {
$startServerBtn.show();
$stopServerBtn.hide();
$restartServerBtn.hide();
}
};
var startServer = function() {
$confWindow.window('loading', true, {
message: 'Starting server...'
});
Webos.ServerCall.websocket.startServer(function() {
$confWindow.window('loading', false);
refreshServerStatus();
});
};
var stopServer = function() {
$confWindow.window('loading', true, {
message: 'Stopping server...'
});
Webos.ServerCall.websocket.stopServer(function() {
$confWindow.window('loading', false);
refreshServerStatus();
});
};
var restartServer = function() {
$confWindow.window('loading', true, {
message: 'Restarting server...'
});
Webos.ServerCall.websocket.restartServer(function() {
$confWindow.window('loading', false);
refreshServerStatus();
});
};
var displayConfig = function(serverStatus) {
for (var controlName in controls) {
if (typeof serverStatus[controlName] != 'undefined') {
controls[controlName][$.webos.widget.get(controls[controlName])]('value', serverStatus[controlName]);
}
}
};
var updateConfig = function() {
$confWindow.window('loading', true, {
message: 'Updating configuration...'
});
Webos.DataFile.loadSystemData('websocket-server', function(configFile) {
for (var controlName in controls) {
configFile.set(controlName, controls[controlName][$.webos.widget.get(controls[controlName])]('value'));
}
configFile.sync(function() {
$confWindow.window('loading', false);
displayConfig(configFile.data());
});
});
};
var displayStatus = function(msg, isErr) {
var iconName = (isErr) ? 'status/warning' : 'status/info';
var $icon = $.w.icon(iconName, 32).css('float', 'left');
$currentStatusText.empty().append($icon, '<strong>'+msg+'</strong>');
};
var gotServerStatus = function(serverStatus) {
displayServerControls(serverStatus);
if (!serverStatus.supported) {
displayStatus('This server doesn\'t support WebSockets.', true);
$noConfig.show();
$form.hide();
return;
}
$noConfig.hide();
$form.show();
displayConfig(serverStatus);
if (!serverStatus.enabled) {
displayStatus('WebSocket server disabled.', true);
return;
}
if (serverStatus.started) {
displayStatus('Server started and listening at port '+serverStatus.port+'.');
} else {
displayStatus('Server not started.');
}
};
var refreshServerStatus = function() {
$confWindow.window('loading', true, {
message: 'Loading server status...'
});
Webos.ServerCall.websocket.getServerStatus(function(serverStatus) {
$confWindow.window('loading', false);
gotServerStatus(serverStatus);
});
};
refreshServerStatus();
}); | symbiose/symbiose | usr/lib/gconf/categories/js/websocket.js | JavaScript | mit | 4,769 |
version https://git-lfs.github.com/spec/v1
oid sha256:1df2ce3afd750f4ce149d41ea399e7abf3df6f46b13b1b9b9e51afd3320dd8f3
size 1022
| yogeshsaroya/new-cdnjs | ajax/libs/reveal.js/2.6.0/plugin/notes/notes.min.js | JavaScript | mit | 129 |
'use strict';
require('dotenv').config();
if(process.env.NODE_ENV === 'test'){
process.env.DB_PASS = '';
}
const express = require('express');
const bodyParser = require('body-parser');
const fallback = require('express-history-api-fallback');
const passport = require('passport');
const session = require('express-session');
const FacebookStrategy = require('passport-facebook').Strategy;
const routes = require('./routes/routes');
const cookieParser = require('cookie-parser');
const webpackMiddleWare = require('./serverConfig/webpackDevMiddleware');
const keys = require('./config');
const app = express();
const root = `${__dirname}/src/client/public`;
const port = process.env.NODE_DEV || process.env.NODE_PROD;
app.use(cookieParser());
passport.serializeUser(function(id, done) {
done(null, id);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new FacebookStrategy({
clientID: keys.clientID,
clientSecret: keys.clientSecret,
callbackURL: keys.callbackURL,
enableProof: true,
profileFields: ['id', 'displayName', 'email']
}, function(accessToken, refreshToken, profile, done){
process.nextTick(function() {
return done(null, profile);
});
}));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: {maxAge: 60000 * 30} //30 minutes
}));
app.use(passport.initialize());
app.use(passport.session());
// webpack watch setup
if(process.env.NODE_ENV !== 'test'){
webpackMiddleWare(app);
}
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.static(root)); // static files
routes(app);
app.use(fallback('index.html', {root}));
app.listen(port, () =>{
console.log(`Listening on: ${port}`);
});
module.exports = app;
| geryegan/musicmksr | server.js | JavaScript | mit | 1,859 |
/*global todomvc */
'use strict';
/**
* Services that persists and retrieves TODOs from localStorage
*/
todomvc.factory('todoStorage', function ($http) {
var STORAGE_ID = 'todos-angularjs';
return {
get: function () {
var url = '/todos';
return $http.get(url);
},
create: function (todo) {
var url = '/todos';
return $http.post(url, todo);
},
update: function (todo) {
var url = '/todos/' + todo.id;
return $http.put(url, todo);
},
delete: function(id) {
var url = '/todos/' + id;
return $http.delete(url);
}
};
});
| thuongdinh/poc-rethinkdb-nodejs | app/public/js/services/todoStorage.js | JavaScript | mit | 606 |
import Ember from 'ember';
export default Ember.SelectOption.extend({
tagName: 'div',
classNames: 'item',
bindData: Ember.on('didInsertElement', function() {
var valuePath = this.get('valuePath');
if (!valuePath) {
return;
}
if (this.$() == null) {
return;
}
this.$().data('value', this.get(valuePath));
}),
unbindData: Ember.on('willDestroyElement', function() {
this.$().removeData('value');
})
});
| slightlytyler/Semantic-UI-Ember | addon/components/ui-dropdown-item.js | JavaScript | mit | 459 |
'use strict';
const Module = require('../../../bot/modules/Module');
const CommandInfo = require('./commands/Info');
const CommandHelp = require('./commands/Help');
class ModuleGeneral extends Module {
constructor(bot) {
super(bot, 'general');
this.register(new CommandInfo(bot));
this.register(new CommandHelp(bot));
}
}
module.exports = ModuleGeneral;
| Archomeda/kormir-discord-bot | bot/modules/general/index.js | JavaScript | mit | 391 |
version https://git-lfs.github.com/spec/v1
oid sha256:7e2c9128a045c70fa14b0d4a1dfecf1be7602363b728393bebebe9faaab26f0f
size 3833
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.3.0/event/event-base-ie.js | JavaScript | mit | 129 |
'use strict';
app.service('Jira', ['$rootScope', '$q', 'HybridStorage', 'Routing', 'Cleanliness', function($rootScope, $q, HybridStorage, Routing, Cleanliness) {
var config = {
routes: {
'fasttrack': {
'url': 'https://akeneo.atlassian.net/rest/api/latest/search?jql=project%20%3D%20::project::%20AND%20issuetype%20%3D%20Bug%20AND%20fixVersion%20%3D%20::version::%20AND%20status%20%3D%20::status::'
},
'projects': {
'url': 'https://akeneo.atlassian.net/rest/api/2/project/'
},
'project': {
'url': 'https://akeneo.atlassian.net/rest/api/2/project/::projectName::/'
}
},
cold: true
};
var service = {
config:config,
getFastTrack: function(projectName, version) {
console.log(version);
console.log(projectName);
var promises = [];
var self = this;
var deferred = $q.defer();
var status = [
{query:'Open', label: 'Todo'},
{query:'Closed', label:'Delivered'},
{query:'Resolved', label:'Done'},
{query:'"In Progress"', label:'In progress'}
];
var fastTrack = {issues: {}, total: 0};
for (var i in status) {
var url = Routing.proxify(Routing.mapParamsToRoute(this.config.routes.fasttrack.url, {
'project': projectName,
'version': version,
'status': status[i].query
}));
if (!this.config.cold) {
Cleanliness.invalidate(url);
}
(function(i) {
promises.push(HybridStorage.get(url).then(function(result) {
fastTrack.issues[status[i].label] = result;
fastTrack.total += result.total;
}));
})(i);
}
this.config.cold = false;
$q.all(promises).then(function() {
deferred.resolve(fastTrack);
});
return deferred.promise;
},
getProjects: function() {
var deferred = $q.defer();
var url = Routing.proxify(Routing.mapParamsToRoute(this.config.routes.projects.url));
console.log(url);
HybridStorage.get(url).then(function(projects) {
deferred.resolve(projects);
});
return deferred.promise;
},
getProject: function(projectName) {
var deferred = $q.defer();
var url = Routing.proxify(Routing.mapParamsToRoute(
this.config.routes.project.url,
{
'projectName': projectName
}
));
console.log(url);
HybridStorage.get(url).then(function(project) {
deferred.resolve(project);
});
return deferred.promise;
}
};
return service;
}]); | juliensnz/dashboard | app/scripts/services/jira.js | JavaScript | mit | 3,106 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
const TEXT_NODE_TYPE = 3;
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
function initModules() {
jest.resetModuleRegistry();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
// Make them available to the helpers.
return {
ReactDOM,
ReactDOMServer,
ReactTestUtils,
};
}
const {
resetModules,
itRenders,
itThrowsWhenRendering,
serverRender,
streamRender,
clientCleanRender,
clientRenderOnServerString,
} = ReactDOMServerIntegrationUtils(initModules);
describe('ReactDOMServerIntegration', () => {
beforeEach(() => {
resetModules();
});
describe('elements and children', function() {
function expectNode(node, type, value) {
expect(node).not.toBe(null);
expect(node.nodeType).toBe(type);
expect(node.nodeValue).toMatch(value);
}
function expectTextNode(node, text) {
expectNode(node, TEXT_NODE_TYPE, text);
}
describe('text children', function() {
itRenders('a div with text', async render => {
const e = await render(<div>Text</div>);
expect(e.tagName).toBe('DIV');
expect(e.childNodes.length).toBe(1);
expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text');
});
itRenders('a div with text with flanking whitespace', async render => {
// prettier-ignore
const e = await render(<div> Text </div>);
expect(e.childNodes.length).toBe(1);
expectNode(e.childNodes[0], TEXT_NODE_TYPE, ' Text ');
});
itRenders('a div with an empty text child', async render => {
const e = await render(<div>{''}</div>);
expect(e.childNodes.length).toBe(0);
});
itRenders('a div with multiple empty text children', async render => {
const e = await render(
<div>
{''}
{''}
{''}
</div>,
);
if (render === serverRender || render === streamRender) {
// For plain server markup result we should have no text nodes if
// they're all empty.
expect(e.childNodes.length).toBe(0);
expect(e.textContent).toBe('');
} else {
expect(e.childNodes.length).toBe(3);
expectTextNode(e.childNodes[0], '');
expectTextNode(e.childNodes[1], '');
expectTextNode(e.childNodes[2], '');
}
});
itRenders('a div with multiple whitespace children', async render => {
// prettier-ignore
const e = await render(<div>{' '}{' '}{' '}</div>);
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
// For plain server markup result we have comments between.
// If we're able to hydrate, they remain.
expect(e.childNodes.length).toBe(5);
expectTextNode(e.childNodes[0], ' ');
expectTextNode(e.childNodes[2], ' ');
expectTextNode(e.childNodes[4], ' ');
} else {
expect(e.childNodes.length).toBe(3);
expectTextNode(e.childNodes[0], ' ');
expectTextNode(e.childNodes[1], ' ');
expectTextNode(e.childNodes[2], ' ');
}
});
itRenders('a div with text sibling to a node', async render => {
const e = await render(
<div>
Text<span>More Text</span>
</div>,
);
let spanNode;
expect(e.childNodes.length).toBe(2);
spanNode = e.childNodes[1];
expectTextNode(e.childNodes[0], 'Text');
expect(spanNode.tagName).toBe('SPAN');
expect(spanNode.childNodes.length).toBe(1);
expectNode(spanNode.firstChild, TEXT_NODE_TYPE, 'More Text');
});
itRenders('a non-standard element with text', async render => {
// This test suite generally assumes that we get exactly
// the same warnings (or none) for all scenarios including
// SSR + innerHTML, hydration, and client-side rendering.
// However this particular warning fires only when creating
// DOM nodes on the client side. We force it to fire early
// so that it gets deduplicated later, and doesn't fail the test.
expect(() => {
ReactDOM.render(<nonstandard />, document.createElement('div'));
}).toErrorDev('The tag <nonstandard> is unrecognized in this browser.');
const e = await render(<nonstandard>Text</nonstandard>);
expect(e.tagName).toBe('NONSTANDARD');
expect(e.childNodes.length).toBe(1);
expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text');
});
itRenders('a custom element with text', async render => {
const e = await render(<custom-element>Text</custom-element>);
expect(e.tagName).toBe('CUSTOM-ELEMENT');
expect(e.childNodes.length).toBe(1);
expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text');
});
itRenders('a leading blank child with a text sibling', async render => {
const e = await render(<div>{''}foo</div>);
if (render === serverRender || render === streamRender) {
expect(e.childNodes.length).toBe(1);
expectTextNode(e.childNodes[0], 'foo');
} else {
expect(e.childNodes.length).toBe(2);
expectTextNode(e.childNodes[0], '');
expectTextNode(e.childNodes[1], 'foo');
}
});
itRenders('a trailing blank child with a text sibling', async render => {
const e = await render(<div>foo{''}</div>);
// with Fiber, there are just two text nodes.
if (render === serverRender || render === streamRender) {
expect(e.childNodes.length).toBe(1);
expectTextNode(e.childNodes[0], 'foo');
} else {
expect(e.childNodes.length).toBe(2);
expectTextNode(e.childNodes[0], 'foo');
expectTextNode(e.childNodes[1], '');
}
});
itRenders('an element with two text children', async render => {
const e = await render(
<div>
{'foo'}
{'bar'}
</div>,
);
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
// In the server render output there's a comment between them.
expect(e.childNodes.length).toBe(3);
expectTextNode(e.childNodes[0], 'foo');
expectTextNode(e.childNodes[2], 'bar');
} else {
expect(e.childNodes.length).toBe(2);
expectTextNode(e.childNodes[0], 'foo');
expectTextNode(e.childNodes[1], 'bar');
}
});
itRenders(
'a component returning text node between two text nodes',
async render => {
const B = () => 'b';
const e = await render(
<div>
{'a'}
<B />
{'c'}
</div>,
);
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
// In the server render output there's a comment between them.
expect(e.childNodes.length).toBe(5);
expectTextNode(e.childNodes[0], 'a');
expectTextNode(e.childNodes[2], 'b');
expectTextNode(e.childNodes[4], 'c');
} else {
expect(e.childNodes.length).toBe(3);
expectTextNode(e.childNodes[0], 'a');
expectTextNode(e.childNodes[1], 'b');
expectTextNode(e.childNodes[2], 'c');
}
},
);
itRenders('a tree with sibling host and text nodes', async render => {
class X extends React.Component {
render() {
return [null, [<Y key="1" />], false];
}
}
function Y() {
return [<Z key="1" />, ['c']];
}
function Z() {
return null;
}
const e = await render(
<div>
{[['a'], 'b']}
<div>
<X key="1" />
d
</div>
e
</div>,
);
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
// In the server render output there's comments between text nodes.
expect(e.childNodes.length).toBe(5);
expectTextNode(e.childNodes[0], 'a');
expectTextNode(e.childNodes[2], 'b');
expect(e.childNodes[3].childNodes.length).toBe(3);
expectTextNode(e.childNodes[3].childNodes[0], 'c');
expectTextNode(e.childNodes[3].childNodes[2], 'd');
expectTextNode(e.childNodes[4], 'e');
} else {
expect(e.childNodes.length).toBe(4);
expectTextNode(e.childNodes[0], 'a');
expectTextNode(e.childNodes[1], 'b');
expect(e.childNodes[2].childNodes.length).toBe(2);
expectTextNode(e.childNodes[2].childNodes[0], 'c');
expectTextNode(e.childNodes[2].childNodes[1], 'd');
expectTextNode(e.childNodes[3], 'e');
}
});
});
describe('number children', function() {
itRenders('a number as single child', async render => {
const e = await render(<div>{3}</div>);
expect(e.textContent).toBe('3');
});
// zero is falsey, so it could look like no children if the code isn't careful.
itRenders('zero as single child', async render => {
const e = await render(<div>{0}</div>);
expect(e.textContent).toBe('0');
});
itRenders('an element with number and text children', async render => {
const e = await render(
<div>
{'foo'}
{40}
</div>,
);
// with Fiber, there are just two text nodes.
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
// In the server markup there's a comment between.
expect(e.childNodes.length).toBe(3);
expectTextNode(e.childNodes[0], 'foo');
expectTextNode(e.childNodes[2], '40');
} else {
expect(e.childNodes.length).toBe(2);
expectTextNode(e.childNodes[0], 'foo');
expectTextNode(e.childNodes[1], '40');
}
});
});
describe('null, false, and undefined children', function() {
itRenders('null single child as blank', async render => {
const e = await render(<div>{null}</div>);
expect(e.childNodes.length).toBe(0);
});
itRenders('false single child as blank', async render => {
const e = await render(<div>{false}</div>);
expect(e.childNodes.length).toBe(0);
});
itRenders('undefined single child as blank', async render => {
const e = await render(<div>{undefined}</div>);
expect(e.childNodes.length).toBe(0);
});
itRenders('a null component children as empty', async render => {
const NullComponent = () => null;
const e = await render(
<div>
<NullComponent />
</div>,
);
expect(e.childNodes.length).toBe(0);
});
itRenders('null children as blank', async render => {
const e = await render(<div>{null}foo</div>);
expect(e.childNodes.length).toBe(1);
expectTextNode(e.childNodes[0], 'foo');
});
itRenders('false children as blank', async render => {
const e = await render(<div>{false}foo</div>);
expect(e.childNodes.length).toBe(1);
expectTextNode(e.childNodes[0], 'foo');
});
itRenders('null and false children together as blank', async render => {
const e = await render(
<div>
{false}
{null}foo{null}
{false}
</div>,
);
expect(e.childNodes.length).toBe(1);
expectTextNode(e.childNodes[0], 'foo');
});
itRenders('only null and false children as blank', async render => {
const e = await render(
<div>
{false}
{null}
{null}
{false}
</div>,
);
expect(e.childNodes.length).toBe(0);
});
});
describe('elements with implicit namespaces', function() {
itRenders('an svg element', async render => {
const e = await render(<svg />);
expect(e.childNodes.length).toBe(0);
expect(e.tagName).toBe('svg');
expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg');
});
itRenders('svg child element with an attribute', async render => {
let e = await render(<svg viewBox="0 0 0 0" />);
expect(e.childNodes.length).toBe(0);
expect(e.tagName).toBe('svg');
expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg');
expect(e.getAttribute('viewBox')).toBe('0 0 0 0');
});
itRenders(
'svg child element with a namespace attribute',
async render => {
let e = await render(
<svg>
<image xlinkHref="http://i.imgur.com/w7GCRPb.png" />
</svg>,
);
e = e.firstChild;
expect(e.childNodes.length).toBe(0);
expect(e.tagName).toBe('image');
expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg');
expect(e.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe(
'http://i.imgur.com/w7GCRPb.png',
);
},
);
itRenders('svg child element with a badly cased alias', async render => {
let e = await render(
<svg>
<image xlinkhref="http://i.imgur.com/w7GCRPb.png" />
</svg>,
1,
);
e = e.firstChild;
expect(e.hasAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe(
false,
);
expect(e.getAttribute('xlinkhref')).toBe(
'http://i.imgur.com/w7GCRPb.png',
);
});
itRenders('svg element with a tabIndex attribute', async render => {
let e = await render(<svg tabIndex="1" />);
expect(e.tabIndex).toBe(1);
});
itRenders(
'svg element with a badly cased tabIndex attribute',
async render => {
let e = await render(<svg tabindex="1" />, 1);
expect(e.tabIndex).toBe(1);
},
);
itRenders('svg element with a mixed case name', async render => {
let e = await render(
<svg>
<filter>
<feMorphology />
</filter>
</svg>,
);
e = e.firstChild.firstChild;
expect(e.childNodes.length).toBe(0);
expect(e.tagName).toBe('feMorphology');
expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg');
});
itRenders('a math element', async render => {
const e = await render(<math />);
expect(e.childNodes.length).toBe(0);
expect(e.tagName).toBe('math');
expect(e.namespaceURI).toBe('http://www.w3.org/1998/Math/MathML');
});
});
// specially wrapped components
// (see the big switch near the beginning ofReactDOMComponent.mountComponent)
itRenders('an img', async render => {
const e = await render(<img />);
expect(e.childNodes.length).toBe(0);
expect(e.nextSibling).toBe(null);
expect(e.tagName).toBe('IMG');
});
itRenders('a button', async render => {
const e = await render(<button />);
expect(e.childNodes.length).toBe(0);
expect(e.nextSibling).toBe(null);
expect(e.tagName).toBe('BUTTON');
});
itRenders('a div with dangerouslySetInnerHTML number', async render => {
// Put dangerouslySetInnerHTML one level deeper because otherwise
// hydrating from a bad markup would cause a mismatch (since we don't
// patch dangerouslySetInnerHTML as text content).
const e = (await render(
<div>
<span dangerouslySetInnerHTML={{__html: 0}} />
</div>,
)).firstChild;
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE);
expect(e.textContent).toBe('0');
});
itRenders('a div with dangerouslySetInnerHTML boolean', async render => {
// Put dangerouslySetInnerHTML one level deeper because otherwise
// hydrating from a bad markup would cause a mismatch (since we don't
// patch dangerouslySetInnerHTML as text content).
const e = (await render(
<div>
<span dangerouslySetInnerHTML={{__html: false}} />
</div>,
)).firstChild;
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE);
expect(e.firstChild.data).toBe('false');
});
itRenders(
'a div with dangerouslySetInnerHTML text string',
async render => {
// Put dangerouslySetInnerHTML one level deeper because otherwise
// hydrating from a bad markup would cause a mismatch (since we don't
// patch dangerouslySetInnerHTML as text content).
const e = (await render(
<div>
<span dangerouslySetInnerHTML={{__html: 'hello'}} />
</div>,
)).firstChild;
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE);
expect(e.textContent).toBe('hello');
},
);
itRenders(
'a div with dangerouslySetInnerHTML element string',
async render => {
const e = await render(
<div dangerouslySetInnerHTML={{__html: "<span id='child'/>"}} />,
);
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.tagName).toBe('SPAN');
expect(e.firstChild.getAttribute('id')).toBe('child');
expect(e.firstChild.childNodes.length).toBe(0);
},
);
itRenders('a div with dangerouslySetInnerHTML object', async render => {
const obj = {
toString() {
return "<span id='child'/>";
},
};
const e = await render(<div dangerouslySetInnerHTML={{__html: obj}} />);
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.tagName).toBe('SPAN');
expect(e.firstChild.getAttribute('id')).toBe('child');
expect(e.firstChild.childNodes.length).toBe(0);
});
itRenders(
'a div with dangerouslySetInnerHTML set to null',
async render => {
const e = await render(
<div dangerouslySetInnerHTML={{__html: null}} />,
);
expect(e.childNodes.length).toBe(0);
},
);
itRenders(
'a div with dangerouslySetInnerHTML set to undefined',
async render => {
const e = await render(
<div dangerouslySetInnerHTML={{__html: undefined}} />,
);
expect(e.childNodes.length).toBe(0);
},
);
itRenders('a noscript with children', async render => {
const e = await render(
<noscript>
<div>Enable JavaScript to run this app.</div>
</noscript>,
);
if (render === clientCleanRender) {
// On the client we ignore the contents of a noscript
expect(e.childNodes.length).toBe(0);
} else {
// On the server or when hydrating the content should be correct
expect(e.childNodes.length).toBe(1);
expect(e.firstChild.textContent).toBe(
'<div>Enable JavaScript to run this app.</div>',
);
}
});
describe('newline-eating elements', function() {
itRenders(
'a newline-eating tag with content not starting with \\n',
async render => {
const e = await render(<pre>Hello</pre>);
expect(e.textContent).toBe('Hello');
},
);
itRenders(
'a newline-eating tag with content starting with \\n',
async render => {
const e = await render(<pre>{'\nHello'}</pre>);
expect(e.textContent).toBe('\nHello');
},
);
itRenders('a normal tag with content starting with \\n', async render => {
const e = await render(<div>{'\nHello'}</div>);
expect(e.textContent).toBe('\nHello');
});
});
describe('different component implementations', function() {
function checkFooDiv(e) {
expect(e.childNodes.length).toBe(1);
expectNode(e.firstChild, TEXT_NODE_TYPE, 'foo');
}
itRenders('stateless components', async render => {
const FunctionComponent = () => <div>foo</div>;
checkFooDiv(await render(<FunctionComponent />));
});
itRenders('ES6 class components', async render => {
class ClassComponent extends React.Component {
render() {
return <div>foo</div>;
}
}
checkFooDiv(await render(<ClassComponent />));
});
itRenders('factory components', async render => {
const FactoryComponent = () => {
return {
render: function() {
return <div>foo</div>;
},
};
};
checkFooDiv(await render(<FactoryComponent />, 1));
});
});
describe('component hierarchies', function() {
itRenders('single child hierarchies of components', async render => {
const Component = props => <div>{props.children}</div>;
let e = await render(
<Component>
<Component>
<Component>
<Component />
</Component>
</Component>
</Component>,
);
for (let i = 0; i < 3; i++) {
expect(e.tagName).toBe('DIV');
expect(e.childNodes.length).toBe(1);
e = e.firstChild;
}
expect(e.tagName).toBe('DIV');
expect(e.childNodes.length).toBe(0);
});
itRenders('multi-child hierarchies of components', async render => {
const Component = props => <div>{props.children}</div>;
const e = await render(
<Component>
<Component>
<Component />
<Component />
</Component>
<Component>
<Component />
<Component />
</Component>
</Component>,
);
expect(e.tagName).toBe('DIV');
expect(e.childNodes.length).toBe(2);
for (let i = 0; i < 2; i++) {
const child = e.childNodes[i];
expect(child.tagName).toBe('DIV');
expect(child.childNodes.length).toBe(2);
for (let j = 0; j < 2; j++) {
const grandchild = child.childNodes[j];
expect(grandchild.tagName).toBe('DIV');
expect(grandchild.childNodes.length).toBe(0);
}
}
});
itRenders('a div with a child', async render => {
const e = await render(
<div id="parent">
<div id="child" />
</div>,
);
expect(e.id).toBe('parent');
expect(e.childNodes.length).toBe(1);
expect(e.childNodes[0].id).toBe('child');
expect(e.childNodes[0].childNodes.length).toBe(0);
});
itRenders('a div with multiple children', async render => {
const e = await render(
<div id="parent">
<div id="child1" />
<div id="child2" />
</div>,
);
expect(e.id).toBe('parent');
expect(e.childNodes.length).toBe(2);
expect(e.childNodes[0].id).toBe('child1');
expect(e.childNodes[0].childNodes.length).toBe(0);
expect(e.childNodes[1].id).toBe('child2');
expect(e.childNodes[1].childNodes.length).toBe(0);
});
itRenders(
'a div with multiple children separated by whitespace',
async render => {
const e = await render(
<div id="parent">
<div id="child1" /> <div id="child2" />
</div>,
);
expect(e.id).toBe('parent');
let child1, child2, textNode;
expect(e.childNodes.length).toBe(3);
child1 = e.childNodes[0];
textNode = e.childNodes[1];
child2 = e.childNodes[2];
expect(child1.id).toBe('child1');
expect(child1.childNodes.length).toBe(0);
expectTextNode(textNode, ' ');
expect(child2.id).toBe('child2');
expect(child2.childNodes.length).toBe(0);
},
);
itRenders(
'a div with a single child surrounded by whitespace',
async render => {
// prettier-ignore
const e = await render(<div id="parent"> <div id="child" /> </div>); // eslint-disable-line no-multi-spaces
let textNode1, child, textNode2;
expect(e.childNodes.length).toBe(3);
textNode1 = e.childNodes[0];
child = e.childNodes[1];
textNode2 = e.childNodes[2];
expect(e.id).toBe('parent');
expectTextNode(textNode1, ' ');
expect(child.id).toBe('child');
expect(child.childNodes.length).toBe(0);
expectTextNode(textNode2, ' ');
},
);
itRenders('a composite with multiple children', async render => {
const Component = props => props.children;
const e = await render(
<Component>{['a', 'b', [undefined], [[false, 'c']]]}</Component>,
);
let parent = e.parentNode;
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
// For plain server markup result we have comments between.
// If we're able to hydrate, they remain.
expect(parent.childNodes.length).toBe(5);
expectTextNode(parent.childNodes[0], 'a');
expectTextNode(parent.childNodes[2], 'b');
expectTextNode(parent.childNodes[4], 'c');
} else {
expect(parent.childNodes.length).toBe(3);
expectTextNode(parent.childNodes[0], 'a');
expectTextNode(parent.childNodes[1], 'b');
expectTextNode(parent.childNodes[2], 'c');
}
});
});
describe('escaping >, <, and &', function() {
itRenders('>,<, and & as single child', async render => {
const e = await render(<div>{'<span>Text"</span>'}</div>);
expect(e.childNodes.length).toBe(1);
expectNode(e.firstChild, TEXT_NODE_TYPE, '<span>Text"</span>');
});
itRenders('>,<, and & as multiple children', async render => {
const e = await render(
<div>
{'<span>Text1"</span>'}
{'<span>Text2"</span>'}
</div>,
);
if (
render === serverRender ||
render === clientRenderOnServerString ||
render === streamRender
) {
expect(e.childNodes.length).toBe(3);
expectTextNode(e.childNodes[0], '<span>Text1"</span>');
expectTextNode(e.childNodes[2], '<span>Text2"</span>');
} else {
expect(e.childNodes.length).toBe(2);
expectTextNode(e.childNodes[0], '<span>Text1"</span>');
expectTextNode(e.childNodes[1], '<span>Text2"</span>');
}
});
});
describe('carriage return and null character', () => {
// HTML parsing normalizes CR and CRLF to LF.
// It also ignores null character.
// https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
// If we have a mismatch, it might be caused by that (and should not be reported).
// We won't be patching up in this case as that matches our past behavior.
itRenders(
'an element with one text child with special characters',
async render => {
const e = await render(<div>{'foo\rbar\r\nbaz\nqux\u0000'}</div>);
if (render === serverRender || render === streamRender) {
expect(e.childNodes.length).toBe(1);
// Everything becomes LF when parsed from server HTML.
// Null character is ignored.
expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar\nbaz\nqux');
} else {
expect(e.childNodes.length).toBe(1);
// Client rendering (or hydration) uses JS value with CR.
// Null character stays.
expectNode(
e.childNodes[0],
TEXT_NODE_TYPE,
'foo\rbar\r\nbaz\nqux\u0000',
);
}
},
);
itRenders(
'an element with two text children with special characters',
async render => {
const e = await render(
<div>
{'foo\rbar'}
{'\r\nbaz\nqux\u0000'}
</div>,
);
if (render === serverRender || render === streamRender) {
// We have three nodes because there is a comment between them.
expect(e.childNodes.length).toBe(3);
// Everything becomes LF when parsed from server HTML.
// Null character is ignored.
expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar');
expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\nbaz\nqux');
} else if (render === clientRenderOnServerString) {
// We have three nodes because there is a comment between them.
expect(e.childNodes.length).toBe(3);
// Hydration uses JS value with CR and null character.
expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar');
expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000');
} else {
expect(e.childNodes.length).toBe(2);
// Client rendering uses JS value with CR and null character.
expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar');
expectNode(e.childNodes[1], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000');
}
},
);
itRenders(
'an element with an attribute value with special characters',
async render => {
const e = await render(<a title={'foo\rbar\r\nbaz\nqux\u0000'} />);
if (
render === serverRender ||
render === streamRender ||
render === clientRenderOnServerString
) {
// Everything becomes LF when parsed from server HTML.
// Null character in an attribute becomes the replacement character.
// Hydration also ends up with LF because we don't patch up attributes.
expect(e.title).toBe('foo\nbar\nbaz\nqux\uFFFD');
} else {
// Client rendering uses JS value with CR and null character.
expect(e.title).toBe('foo\rbar\r\nbaz\nqux\u0000');
}
},
);
});
describe('components that throw errors', function() {
itThrowsWhenRendering(
'a function returning undefined',
async render => {
const UndefinedComponent = () => undefined;
await render(<UndefinedComponent />, 1);
},
'UndefinedComponent(...): Nothing was returned from render. ' +
'This usually means a return statement is missing. Or, to ' +
'render nothing, return null.',
);
itThrowsWhenRendering(
'a class returning undefined',
async render => {
class UndefinedComponent extends React.Component {
render() {
return undefined;
}
}
await render(<UndefinedComponent />, 1);
},
'UndefinedComponent(...): Nothing was returned from render. ' +
'This usually means a return statement is missing. Or, to ' +
'render nothing, return null.',
);
itThrowsWhenRendering(
'a function returning an object',
async render => {
const ObjectComponent = () => ({x: 123});
await render(<ObjectComponent />, 1);
},
'Objects are not valid as a React child (found: object with keys {x}).' +
(__DEV__
? ' If you meant to render a collection of children, use ' +
'an array instead.'
: ''),
);
itThrowsWhenRendering(
'a class returning an object',
async render => {
class ObjectComponent extends React.Component {
render() {
return {x: 123};
}
}
await render(<ObjectComponent />, 1);
},
'Objects are not valid as a React child (found: object with keys {x}).' +
(__DEV__
? ' If you meant to render a collection of children, use ' +
'an array instead.'
: ''),
);
itThrowsWhenRendering(
'top-level object',
async render => {
await render({x: 123});
},
'Objects are not valid as a React child (found: object with keys {x}).' +
(__DEV__
? ' If you meant to render a collection of children, use ' +
'an array instead.'
: ''),
);
});
describe('badly-typed elements', function() {
itThrowsWhenRendering(
'object',
async render => {
let EmptyComponent = {};
expect(() => {
EmptyComponent = <EmptyComponent />;
}).toErrorDev(
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: object. You likely forgot to export your ' +
"component from the file it's defined in, or you might have mixed up " +
'default and named imports.',
{withoutStack: true},
);
await render(EmptyComponent);
},
'Element type is invalid: expected a string (for built-in components) or a class/function ' +
'(for composite components) but got: object.' +
(__DEV__
? " You likely forgot to export your component from the file it's defined in, " +
'or you might have mixed up default and named imports.'
: ''),
);
itThrowsWhenRendering(
'null',
async render => {
let NullComponent = null;
expect(() => {
NullComponent = <NullComponent />;
}).toErrorDev(
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: null.',
{withoutStack: true},
);
await render(NullComponent);
},
'Element type is invalid: expected a string (for built-in components) or a class/function ' +
'(for composite components) but got: null',
);
itThrowsWhenRendering(
'undefined',
async render => {
let UndefinedComponent = undefined;
expect(() => {
UndefinedComponent = <UndefinedComponent />;
}).toErrorDev(
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' +
"component from the file it's defined in, or you might have mixed up " +
'default and named imports.',
{withoutStack: true},
);
await render(UndefinedComponent);
},
'Element type is invalid: expected a string (for built-in components) or a class/function ' +
'(for composite components) but got: undefined.' +
(__DEV__
? " You likely forgot to export your component from the file it's defined in, " +
'or you might have mixed up default and named imports.'
: ''),
);
});
});
});
| Simek/react | packages/react-dom/src/__tests__/ReactDOMServerIntegrationElements-test.js | JavaScript | mit | 36,503 |
/*
* This is the main file where we program the application JS. This code is then
* processed through Browserify to protect namespace.
*/
// Require some libs.
var $ = require('jquery'),
crossfilter = require('crossfilter'),
console = require('console'),
categoryFilter = require("./CategoryFilter"),
proximityFilter = require("./ProximityFilter"),
regionFilter = require("./RegionFilter"),
UserLocation = require('./UserLocation');
// Mapbox doesn't need its own var - it automatically attaches to Leaflet's L.
require('mapbox.js');
// Use Awesome Markers lib to produce font-icon map markers
require('./leaflet.awesome-markers.js');
// Marker clustering
require('../node_modules/leaflet.markercluster/dist/leaflet.markercluster.js');
// Select user location control
require('./SelectUserLocationControl');
// File system
var fs = require('fs');
// Initialize the map, using Affinity Bridge's mapbox account.
var map = L.mapbox.map('map', 'affinitybridge.ia7h38nj');
// Object that holds user location - adds a layer with user's location marker
var myLocation = new UserLocation(map);
map.on('load', function() {
// Try to add user location marker
getUserLocation();
});
// Initialize the empty layer for the markers, and add it to the map.
var clusterLayer = new L.MarkerClusterGroup({zoomToBoundsOnClick: false, spiderfyDistanceMultiplier: 2, showCoverageOnHover: false})
.addTo(map);
// When user clicks on a cluster, zoom directly to its bounds. If we don't do this,
// they have to click repeatedly to zoom in enough for the cluster to spiderfy.
clusterLayer.on('clusterclick', function (a) {
// Close any popups that are open already. This helps if we came via "show on map" link,
// which spawns an unbound popup.
map.closePopup();
// If the markers in this cluster are all in the same place, spiderfy on click.
var bounds = a.layer.getBounds();
if (bounds._northEast.equals(bounds._southWest)) {
a.layer.spiderfy();
} else {
// If the markers in this cluster are NOT all in the same place, zoom in on them.
a.layer.zoomToBounds();
}
});
var polygonLayer = L.geoJson();
map.addLayer(polygonLayer);
// Match possible Activity Categories to Humanitarian Font icons.
var iconGlyphs = {
'CASH': {glyph: 'ocha-sector-cash', markerColor: '#a48658' },
'EDUCATION': {glyph: 'ocha-sector-education', markerColor: '#c00000' },
'FOOD': {glyph: 'ocha-sector-foodsecurity', markerColor: '#006600' },
'HEALTH': {glyph: 'ocha-sector-health', markerColor: '#08a1d9' },
'NFI': {glyph: 'ocha-item-reliefgood', markerColor: '#f96a1b' },
'PROTECTION': {glyph: 'ocha-sector-protection', markerColor: '#1f497d' },
'SHELTER': {glyph: 'ocha-sector-shelter', markerColor: '#989aac' },
'WASH': {glyph: 'ocha-sector-wash', markerColor: '#7030a0' }
};
var iconObjects = {};
// Create the icon objects. We'll reuse the same icon for all markers in the same category.
for (var category in iconGlyphs) {
iconObjects[category] = L.AwesomeMarkers.icon({
icon: iconGlyphs[category].glyph,
prefix: 'icon', // necessary because Humanitarian Fonts prefixes its icon names with "icon"
iconColor: iconGlyphs[category].markerColor,
markerColor: "white",
extraClasses: category
});
}
// Define the filters
var cf = crossfilter();
var cf_activityName = categoryFilter({
container: 'activityName',
type: 'radio',
key: 'activityName',
all: true
}, cf);
var cf_referralRequired = categoryFilter({
container: 'referralRequired',
type: 'radio',
key: 'Referral required'
}, cf);
var cf_proximity = proximityFilter({
container: 'proximity',
map: map,
userLocation: myLocation
}, cf);
var cf_region = regionFilter({
container: 'region',
type: 'radio',
all: true,
map: map,
key: 'region',
nameProperty: 'adm1_name',
regionsLayer: polygonLayer
}, cf);
var cf_partnerName = categoryFilter({
container: 'partnerName',
type: 'checkbox',
key: 'partnerName'
}, cf);
// Read the polygon file.
// TODO: use these polygons as the basis for a filter/zoom tool
/* Commenting the polygons out for now because they aren't clickable yet */
jQuery.getJSON( "src/polygons.json", function( polygonData ) {
// Create the polygon layer and add to the map.
polygonLayer.addData(polygonData);
cf_region.update();
});
// Special meta-dimension for our crossFilter dimensions, used to grab the final set
// of data with all other dimensions' filters applied.
var metaDimension = cf.dimension(function (f) { return f.properties.activityName; });
// Whenever the user changes their selection in the filters, run our update() method.
// (In other words, bind the update() method to the "update" event on the category filter.)
cf_activityName.on('update', update);
cf_referralRequired.on('update', update);
cf_proximity.on('update', update);
cf_region.on('update', update);
cf_partnerName.on('update', update);
// Show/hide search filters togglers
$("#search-map a").click(function(e) {
var target = this.getAttribute('href');
e.preventDefault();
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(target).slideUp(function(e) {
$(this).removeClass('active');
});
}
else {
$(this).addClass('active');
$(target).slideDown(function(e) {
$(this).addClass('active');
});
}
});
// Close filter containers by clicking outside
$(document).mouseup(function (e) {
var container = $(".filter-contents.active");
// if the target of the click isn't the container nor a descendant of the container
if (container.length && !container.is(e.target) && container.has(e.target).length === 0) {
var target = container.attr('id');
// make sure w are not clicking on the actual trigger
if ($('a[href="#' + target + '"]')[0] != $(e.target)[0]) {
$('a[href="#' + target + '"]').removeClass('active');
container.slideUp(function(e) {
$(this).removeClass('active');
});
}
}
});
// Show/hide organizations
$(".advanced-search > h4").click(function(e) {
var $parent = $(this).parent();
$filter = $parent.children('.filter');
e.preventDefault();
if ($parent.hasClass('active')) {
$filter.slideUp(function(e) {
$parent.removeClass('active');
});
}
else {
$filter.slideDown(function(e) {
$parent.addClass('active');
});
}
});
// Map/list view toggler - make "map" active on initial page load.
$("#mapToggle").addClass("active");
// Bind click of toggler to swapping visibility of map and list.
$("#map-list-toggler").click(function(e) {
e.preventDefault();
$("#map").toggle();
$("#list").toggle();
$("#mapToggle").toggleClass("active");
$("#listToggle").toggleClass("active");
});
// When a popup is opened, bind its "show details" link to switch to list view.
map.on('popupopen', function(e){
// We already gave the popups the service's unique ID as their className attribute.
var id = e.popup.options.className;
$("#show-details-" + id).click(function() {
// If "show details" is clicked, expand the corresponding item in the still-hidden list view.
$("#article-" + id).addClass('expand');
// Since the article is expanded, the details toggle link should say "Hide details".
$("#article-" + id).find('.show-details').html("Hide details");
// Switch to list view.
$("#map-list-toggler").click();
// Scroll to the item.
$('html, body').animate({
scrollTop: $("#article-" + id).offset().top
}, 500);
});
});
// If all npm modules have been installed and gulp has been run, we should have
// a pre-compiled single file containing the JSON from all our sources in sources.txt.
// Get that pre-compiled JSON, and loop through it creating the markers.
jQuery.getJSON( "src/compiled.json", function( data ) {
$.each( data, function( key, feature ) {
// Create marker and add it to the cluster layer.
var serviceMarker = L.marker(feature.geometry.coordinates.reverse(),
{icon: iconObjects[feature.properties.activityCategory]});
serviceMarker.addTo(clusterLayer);
// Make the popup, and bind it to the marker. Add the service's unique ID
// as a classname; we'll use it later for the "Show details" action.
serviceMarker.bindPopup(renderServiceText(feature, "marker"), {className:feature.id});
// Add the marker to the feature object, so we can re-use the same marker during render().
feature.properties.marker = serviceMarker;
});
// Add the new data to the crossfilter.
cf.add(data);
// Add the markers to the map.
update();
});
// Functions...
// Update the markers and filters based on the user's filter input.
function update() {
// Update the filters.
cf_activityName.update();
cf_referralRequired.update();
//cf_proximity.update();
//cf_region.update();
cf_partnerName.update();
// Add the markers to the map.
render();
}
// Try getting user's location using map.locate() function
// if gps is disabled or not available adds a map control
// for manual selection (+ bind user-location-selected event)
function getUserLocation() {
map.on("locationfound", function(evt) {
updateMyLocation(evt.latlng);
});
map.on("locationerror", function(evt) {
L.control.selectUserLocation().addTo(map);
map.on('user-location-selected', function(evt) {
updateMyLocation(evt.latlng);
});
});
map.locate();
}
// Set user's location with lat/lng coming from gps or manual selection
function updateMyLocation(l) {
myLocation.setLocation(l);
}
// Clear the data and re-render.
function render() {
// Clear all the map markers.
clusterLayer.clearLayers();
// Initialize the list-view output.
var listOutput = '<h3 class="hide">Services</h3>';
// Initialize a list where we'll store the current markers for easy reference when
// building the "show on map" functionality. TODO: can we streamline this out?
var markers = {};
// Loop through the filtered results, adding the markers back to the map.
metaDimension.top(Infinity).forEach( function (feature) {
// Add the filtered markers back to the map's data layer
clusterLayer.addLayer(feature.properties.marker);
// Store the marker for easy reference.
markers[feature.id] = feature.properties.marker;
// Build the output for the filtered list view
listOutput += renderServiceText(feature, "list");
} );
// Replace the contents of the list div with this new, filtered output.
$('#list').html(listOutput);
// According functionality for the list - expand item when its header is clicked
$(".serviceText > header").click(function(event) {
event.preventDefault();
$(this).parent().toggleClass('expand');
// Toggle the text of the "Show details" / "Hide details" link
if ($(this).find('.show-details').html() === "Show details") {
$(this).find('.show-details').html("Hide details");
} else {
$(this).find('.show-details').html("Show details");
}
});
// Bind "show on map" behavior. Do this here because now the list exists.
$(".show-on-map").click(function(e) {
// Get the unique ID of this service.
var id = e.target.id;
// Close any popups that are open already.
map.closePopup();
// Fire the map/list toggler click event, to switch to viewing the map.
$("#map-list-toggler").click();
// Pan and zoom the map.
map.panTo(markers[id]._latlng);
if (map.getZoom() < 12) { map.setZoom(12); }
// Clone the popup for this marker. We'll show it at the correct lat-long, but
// unbound from the marker. We do this in case the marker is in a cluster.
var unboundPopup = markers[id].getPopup();
// Send the service's unique ID as the className of the popup, so that the "Show
// details" binding will work as usual when the popupopen event fires; also, offset
// the Y position so the popup is a little bit above the marker or cluster.
map.openPopup(L.popup({className:id, offset: new L.Point(0,-25)})
.setLatLng(markers[id]._latlng)
.setContent(markers[id].getPopup()._content));
});
}
// Prepare text output for a single service, to show in the map popups or the list view.
function renderServiceText(feature, style) {
// Get the partner logo, if any.
partnerName = feature.properties.partnerName;
var logo = partnerName;
var logoUrl = './src/images/partner/' + partnerName.toLowerCase().replace(' ', '') + '.jpg';
var http = new XMLHttpRequest();
http.open('HEAD', logoUrl, false);
http.send();
if (http.status != 404) {
logo = '<img src="' + logoUrl + '" alt="' + partnerName + '" />';
}
// Prepare the office hours output.
var hours = '<strong>Hours:</strong> ';
var hourOpen = '';
var hourClosed = '';
for (var hoItem in feature.properties["8. Office Open at"]) {
if (feature.properties["8. Office Open at"][hoItem] === true) {
hourOpen = hoItem;
}
}
for (var hcItem in feature.properties["9. Office close at"]) {
if (feature.properties["9. Office close at"][hcItem] === true) {
hourClosed = hcItem;
}
}
// If we have hours, show them as compact as possible.
if (hourOpen) {
// If we have open time but no close time, say "Open at X o'clock"; if we
// have both, show "X o'clock to X o'clock".
hours = hourClosed ?
hours += hourOpen + ' - ' + hourClosed.replace('Close at', '') :
hours + 'Open at ' + hourOpen;
} else {
// If we have no open time but yes close time, show close time only; if we have
// neither, say "unknown".
hours = hourClosed ? hours += hourClosed : hours + 'unknown';
}
// Create meta-field for better display of indicators.
feature.properties["x. Activity Details"] = feature.properties.indicators;
// Make a list of the fields we want to show - lots of fields for this list view,
// not so many for the map-marker-popup view.
var fields = (style == 'list') ? {
"x. Activity Details": {'section': 'header'},
"10. Referral Method": {'section': 'content'},
"6. Availability": {'section': 'content'},
"7. Availability Day": {'section': 'content'},
"startDate": {'section': 'content', 'label': 'Start Date'},
"endDate": {'section': 'content', 'label': 'End Date'},
"1. Registration Type Requirement": {'section': 'content'},
"2. Nationality": {'section': 'content'},
"3. Intake Criteria": {'section': 'content'},
"4. Accessibility": {'section': 'content'},
"5. Coverage": {'section': 'content'},
"14. Feedback delay": {'section': 'content'},
"11. Immediate Next step response after referal": {'section': 'content'},
"12. Response delay after referrals": {'section': 'content'},
"13. Feedback Mechanism": {'section': 'content'}
}
: {
"x. Activity Details": {'section': 'header'},
"10. Referral Method": {'section': 'header'}
};
// Loop through our list of fields, preparing output for display.
var headerOutput = '';
var contentOutput = '';
for (var field in fields) {
// Get the field items
values = feature.properties[field];
var fieldOutput = '';
// Strip the leading numeral from the field name.
var fieldName = field.substr(field.indexOf(" ") + 1);
// Skip empty fields.
if (values) {
// Some fields have object values. These we must loop through.
if (typeof values === 'object') {
if (Object.getOwnPropertyNames(values).length) {
// Loop through items, and if value is TRUE, add label to the output.
for (var lineItem in values) {
// Checking if the line item value is TRUE
if (values[lineItem]) {
fieldOutput += lineItem + ' ';
}
}
}
// Other fields have a string for a value.
} else if (typeof values === 'string') {
fieldName = fields[field].label;
fieldOutput = values;
}
}
// Wrap the output with a label. If no output, say unknown.
if (fieldOutput === '') { fieldOutput = "unknown"; }
fieldOutput = '<p><strong>' + fieldName + ':</strong> ' + fieldOutput + '</p>';
// Add the field output to the appropriate section.
if (fields[field].section == 'header') {
headerOutput += fieldOutput;
} else {
contentOutput += fieldOutput;
}
}
// Get the activity-category icon.
activityCategory = feature.properties.activityCategory; // eg "CASH"
var glyph = '<i class="glyphicon icon-' + iconGlyphs[activityCategory].glyph + '"></i>';
// In the list view only, the articles must have unique IDs so that we can scroll directly to them
// when someone clicks the "Show details" link in a map marker.
var articleIDattribute = '';
var toggleLinks = '<a id="show-details-' + feature.id + '" href="#">Show details</a>';
// If this is for a marker popup, add a "Show details" link that will take us to the list view.
if (style == 'list') {
// Whereas if this if for list view, add a link to show this item on the map.
toggleLinks = '<a class="show-on-map" id="' + feature.id + '" href="#">Show on map</a> ' +
'<a class="show-details" id="show-details-' + feature.id + '" href="#">Show details</a> ';
activityInfoLink = '<a class="show-activity-info" href="https://www.syrianrefugeeresponse.org/resources/sites/points?feature=' + feature.id + '">Show on ActivityInfo</a>';
articleIDattribute = ' id="article-' + feature.id + '"';
}
// Assemble the article header.
var header = '<header>' + logo + '<h3>' + glyph + feature.properties.locationName + ': ' + feature.properties.activityName + '</h3>' + toggleLinks + '<p class="hours">' + hours + '</p>' + headerOutput + '</header>';
// Preserve the line breaks in the original comment, but strip extra breaks from beginning and end.
var comments = feature.properties.comments ?
feature.properties.comments.trim().replace(/\r\n|\n|\r/g, '<br />') : '';
// Assemble the article content (for list view only).
var content = (style == 'list') ? '<div class="content" id="details-' + feature.id + '">' + contentOutput + '<div class="comments">' + comments + '</div>' + activityInfoLink + '</div>' : '';
return '<article class="serviceText"' + articleIDattribute + '>' + header + content + '</article>';
}
| unhcr-jordan/services-advisor | src/index.js | JavaScript | mit | 19,279 |
/**
* CODE DEPENDENCY: P5.Play Library
*/
var ballerina;
function preload(){
//create an animation from a sequence of numbered images
//pass the first and the last file name and it will try to find the ones in between
ballerina = loadAnimation("assets/out-00000.png", "assets/out-00012.png");
}
function setup() {
createCanvas(windowWidth,windowHeight);
}
function draw() {
//specify the animation instance and its x,y position
//animation() will update the animation frame as well
animation(ballerina, width/2, height/2);
} | IDMNYU/DM-GY6063A-Creative-Coding | week_12/09_p5playAnimation/sketch.js | JavaScript | mit | 538 |
var searchData=
[
['tail',['tail',['../structgraph.html#ae0d45355657d09a8515fdb97c3c46938',1,'graph']]],
['tree_5fpred',['tree_pred',['../structgraph.html#ad531dc27dac0b3cc7965f070e1ba88f2',1,'graph']]]
];
| appfs/appfs | Shrive/ex10/dox/html/search/variables_8.js | JavaScript | mit | 210 |
function StarMap(scene)
{
// graphics object (ccpwgl_int.EveTransform)
this.model = null;
// particle system from underneath this.model
this.stars = null;
// distance range parameter for fading stars in a distance
this.distanceRange = new ccpwgl_int.Tw2Vector4Parameter();
this.distanceRange.name = 'distanceRange';
// corners of stars bounding box
this.corners = [];
// static map data from star map generator
this.mapData = null;
// data set texture (ccpwgl_int.Tw2TextureRes)
this.dataSet = null;
// data set texture size
this.dataSetSize = new Float32Array([1024, 1024]);
// particle size (min and max)
this.particleSize = new Float32Array([30, 30]);
// offsets into the data (offset0, offset1, mix)
this.dataOffset = vec3.create();
// color for jump routes
this.jumpRoutesColor = quat4.create([1, 1, 1, 0.1]);
var self = this;
scene.loadObject(
'res:/graphics/starmap/starmap.red',
function ()
{
var obj = this.wrappedObjects[0];
self.model = obj;
self.stars = obj.particleSystems[0];
var starEffect = obj.mesh.additiveAreas[0].effect;
starEffect.parameters['distanceRange'] = self.distanceRange;
starEffect.parameters['ParticleSize'] = new ccpwgl_int.Tw2Vector2Parameter('ParticleSize', self.particleSize);
starEffect.parameters['DataOffset'] = new ccpwgl_int.Tw2Vector3Parameter('DataOffset', self.dataOffset);
starEffect.parameters['DataSize'] = new ccpwgl_int.Tw2Vector2Parameter('DataSize', self.dataSetSize);
if (self.dataSet)
{
starEffect.parameters['ParticleData'].SetTexturePath(self.dataSet.path);
}
starEffect.BindParameters();
var lineEffect = obj.children[0].mesh.transparentAreas[0].effect;
lineEffect.parameters['LineColor'] = new ccpwgl_int.Tw2Vector4Parameter('LineColor', self.jumpRoutesColor);
obj.particleEmitters[0].geometryResource.RegisterNotification(self);
}
);
// internal (private)
this.RebuildCachedData = function (obj)
{
if (obj == this.dataSet)
{
this.dataSetSize[0] = obj.width;
this.dataSetSize[1] = obj.height;
if (this.model)
{
var starEffect = this.model.mesh.additiveAreas[0].effect;
starEffect.parameters['DataSize'].SetValue(this.dataSetSize);
}
}
else
{
this.mapData = obj.meshes[0].bufferData;
}
}
// Assigns new data set
// texturePath - res path to particle data texture
// minStarSize, maxStarSize - star sizes for alpha 0 and 255 in data set texture
this.SetDataSet = function (texturePath, minStarSize, maxStarSize)
{
this.dataCanvas = null;
this.dataSet = ccpwgl_int.resMan.GetResource(texturePath);
this.dataSet.RegisterNotification(this);
if (this.dataSet.IsGood())
{
this.RebuildCachedData(this.dataSet);
}
this.particleSize[0] = minStarSize;
this.particleSize[1] = maxStarSize;
if (this.model)
{
var starEffect = this.model.mesh.additiveAreas[0].effect;
starEffect.parameters['ParticleData'].SetTexturePath(texturePath);
starEffect.parameters['ParticleSize'].SetValue(this.particleSize);
}
}
this.SetStarColor = function (starID, colorAndSize, offset)
{
if (!this.dataSet.IsGood())
{
return;
}
if (!this.stars || !this.stars.aliveCount)
{
return null;
}
var index = this.stars.aliveCount * offset + starID;
var x = index % this.dataSet.width;
var y = Math.floor(index / this.dataSet.width);
var d = ccpwgl_int.device;
d.gl.bindTexture(d.gl.TEXTURE_2D, this.dataSet.texture);
d.gl.texSubImage2D(d.gl.TEXTURE_2D, 0, x, y, 1, 1, d.gl.RGBA, d.gl.UNSIGNED_CHAR, colorAndSize)
d.gl.bindTexture(d.gl.TEXTURE_2D, null);
}
// For animation/timeline
// set offsets into the data texture for previous and next data sets
// mix is the mix between them
this.SetDataOffset = function (offset0, offset1, mix)
{
this.dataOffset[0] = offset0;
this.dataOffset[1] = offset1;
this.dataOffset[2] = mix;
if (this.model)
{
var starEffect = this.model.mesh.additiveAreas[0].effect;
starEffect.parameters['DataOffset'].SetValue(this.dataOffset);
}
}
// constant color for jump routes
this.SetJumpRoutesColor = function (color)
{
this.jumpRoutesColor = color;
if (this.model)
{
var lineEffect = this.model.children[0].mesh.transparentAreas[0].effect;
lineEffect.parameters['LineColor'].SetValue(this.jumpRoutesColor);
}
}
this.Update = function ()
{
if (this.corners.length == 0)
{
if (this.stars && self.stars.aliveCount)
{
var aabbMin = vec3.create();
var aabbMax = vec3.create();
this.stars.GetBoundingBox(aabbMin, aabbMax);
this.corners.push(quat4.create([aabbMin[0], aabbMax[1], aabbMin[2], 1]));
this.corners.push(quat4.create([aabbMin[0], aabbMin[1], aabbMax[2], 1]));
this.corners.push(quat4.create([aabbMin[0], aabbMax[1], aabbMax[2], 1]));
this.corners.push(quat4.create([aabbMax[0], aabbMin[1], aabbMin[2], 1]));
this.corners.push(quat4.create([aabbMax[0], aabbMax[1], aabbMin[2], 1]));
this.corners.push(quat4.create([aabbMax[0], aabbMin[1], aabbMax[2], 1]));
this.corners.push(quat4.create([aabbMax[0], aabbMax[1], aabbMax[2], 1]));
}
}
if (this.corners.length == 0)
{
return;
}
var tmp = quat4.create();
var znear = 0;
var zfar = 0;
for (var i = 0; i < this.corners.length; ++i)
{
mat4.multiplyVec4(ccpwgl_int.device.view, this.corners[i], tmp);
var l = -tmp[2];
if (i == 0 || znear > l)
{
znear = l;
}
if (i == 0 || zfar < l)
{
zfar = l;
}
}
znear = Math.max(znear, 0);
this.distanceRange.SetValue([znear, 1.0 / (zfar - znear), 0, 0]);
}
this.Pick = function (x, y)
{
if (!this.stars || !self.stars.aliveCount)
{
return null;
}
var viewProjInv = mat4.inverse(mat4.multiply(ccpwgl_int.device.projection, ccpwgl_int.device.view, mat4.create()));
var end = quat4.create([(x / ccpwgl_int.device.viewportWidth) * 2 - 1, -(y / ccpwgl_int.device.viewportHeight) * 2 + 1, 1, 1]);
mat4.multiplyVec4(viewProjInv, end);
vec3.scale(end, 1.0 / end[3]);
var eye = ccpwgl_int.device.eyePosition;
vec3.normalize(vec3.subtract(end, eye));
var closest = -1;
var closestDist = 0;
var position = this.stars.GetElement(ccpwgl_int.Tw2ParticleElementDeclaration.POSITION);
var tmp1 = vec3.create();
var tmp2 = vec3.create();
var pc = vec3.create();
var fov = Math.atan(1.0 / ccpwgl_int.device.projection[5]);
var closestPos;
for (var i = 0; i < this.stars.aliveCount; ++i)
{
var pos = position.buffer.subarray(position.offset, position.offset + 3);
vec3.subtract(pos, eye, pc);
var t = vec3.dot(end, pc);
if (t < 0)
{
position.offset += position.instanceStride;
continue;
}
var p = vec3.scale(end, t, tmp1);
var d = vec3.subtract(p, pc, tmp2);
var l = Math.sqrt(vec3.dot(d, d));
var distSq = vec3.dot(pc, pc);
var fovHeight = Math.sin(fov) * distSq;
var scale = 0.2274 * Math.pow(Math.abs(fovHeight), 0.185);
if (l < 15 * scale)
{
if (closest < 0 || closestDist > t)
{
closest = i;
closestDist = t;
closestPos = pos;
}
}
position.offset += position.instanceStride;
}
if (closest >= 0)
{
console.log(closest, closest * 5 + 4, this.mapData[closest * 5 + 4]);
console.log(pos);
return [closest, closestPos];
}
else
{
return null;
}
}
} | reactormonk/ccpwgl | src/test/StarMap.js | JavaScript | mit | 8,679 |
var assert = require('assert');
var web3 = require('web3');
// https://web3js.readthedocs.io/en/v1.2.0/web3-utils.html#bn
// https://github.com/indutny/bn.js/
var BN = web3.utils.BN;
const nl = {
'0': '0x0000000000000000000000000000000000000000000000000000000000000000',
'1': '0x0000000000000000000000000000000000000000000000000000000000000001',
'9007199254740992': '0x0000000000000000000000000000000000000000000000000020000000000000',
'1000000000000000000': '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000',
'999000000000000000000': '0x00000000000000000000000000000000000000000000003627e8f712373c0000',
'1000000000000000000000000000': '0x0000000000000000000000000000000000000000033b2e3c9fd0803ce8000000',
'115792089237316195423570985008687907853269984665640564039457584007913129639935': '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
}
for (const [key, value] of Object.entries(nl)) {
console.log(value, key);
const n = new BN(key);
const x = n.toBuffer('big', 32);
assert.equal('0x' + x.toString('hex'), value);
const n2 = new BN(x);
assert.equal(n2.cmp(n), 0);
}
/*
var BigNumber = require('bignumber.js');
var eth_util = require("ethereumjs-util");
var nr = new BigNumber('35000000000000000000');
console.log(nr);
console.log(nr.toString());
console.log(nr.toString(16));
var nr2 = new BN('35000000000000000000');
console.log(nr2);
console.log(web3.utils.toHex(nr2));
console.log(web3.utils.padLeft(web3.utils.toHex(nr2), 64));
console.log(eth_util.toBuffer(web3.utils.padLeft(web3.utils.toHex(nr2), 32)));
console.log(nr2.toBuffer('big', 32));
*/ | tavendo/AutobahnJS | packages/autobahn-xbr/test/eip712/test_uint256.js | JavaScript | mit | 1,661 |
var ContextMenu = require('./ContextMenu');
var appendNodeFactory = require('./appendNodeFactory');
var util = require('./util');
/**
* @constructor Node
* Create a new Node
* @param {./treemode} editor
* @param {Object} [params] Can contain parameters:
* {string} field
* {boolean} fieldEditable
* {*} value
* {String} type Can have values 'auto', 'array',
* 'object', or 'string'.
*/
function Node (editor, params) {
/** @type {./treemode} */
this.editor = editor;
this.dom = {};
this.expanded = false;
if(params && (params instanceof Object)) {
this.setField(params.field, params.fieldEditable);
this.setValue(params.value, params.type);
}
else {
this.setField('');
this.setValue(null);
}
this._debouncedOnChangeValue = util.debounce(this._onChangeValue.bind(this), Node.prototype.DEBOUNCE_INTERVAL);
this._debouncedOnChangeField = util.debounce(this._onChangeField.bind(this), Node.prototype.DEBOUNCE_INTERVAL);
}
// debounce interval for keyboard input in milliseconds
Node.prototype.DEBOUNCE_INTERVAL = 150;
/**
* Determine whether the field and/or value of this node are editable
* @private
*/
Node.prototype._updateEditability = function () {
this.editable = {
field: true,
value: true
};
if (this.editor) {
this.editable.field = this.editor.options.mode === 'tree';
this.editable.value = this.editor.options.mode !== 'view';
if ((this.editor.options.mode === 'tree' || this.editor.options.mode === 'form') &&
(typeof this.editor.options.onEditable === 'function')) {
var editable = this.editor.options.onEditable({
field: this.field,
value: this.value,
path: this.getFieldsPath()
});
if (typeof editable === 'boolean') {
this.editable.field = editable;
this.editable.value = editable;
}
else {
if (typeof editable.field === 'boolean') this.editable.field = editable.field;
if (typeof editable.value === 'boolean') this.editable.value = editable.value;
}
}
}
};
/**
* Get the path of this node
* @return {String[]} Array containing the path to this node
*/
Node.prototype.getFieldsPath = function () {
var node = this;
var path = [];
while (node) {
var field = node.field != undefined ? node.field : node.index;
if (field !== undefined) {
path.unshift(field);
}
node = node.parent;
}
return path;
};
/**
* Find a Node from a JSON path like '.items[3].name'
* @param {string} jsonPath
* @return {Node | null} Returns the Node when found, returns null if not found
*/
Node.prototype.findNode = function (jsonPath) {
var path = util.parsePath(jsonPath);
var node = this;
while (node && path.length > 0) {
var prop = path.shift();
if (typeof prop === 'number') {
if (node.type !== 'array') {
throw new Error('Cannot get child node at index ' + prop + ': node is no array');
}
node = node.childs[prop];
}
else { // string
if (node.type !== 'object') {
throw new Error('Cannot get child node ' + prop + ': node is no object');
}
node = node.childs.filter(function (child) {
return child.field === prop;
})[0];
}
}
return node;
};
/**
* Find all parents of this node. The parents are ordered from root node towards
* the original node.
* @return {Array.<Node>}
*/
Node.prototype.findParents = function () {
var parents = [];
var parent = this.parent;
while (parent) {
parents.unshift(parent);
parent = parent.parent;
}
return parents;
};
/**
*
* @param {{dataPath: string, keyword: string, message: string, params: Object, schemaPath: string} | null} error
* @param {Node} [child] When this is the error of a parent node, pointing
* to an invalid child node, the child node itself
* can be provided. If provided, clicking the error
* icon will set focus to the invalid child node.
*/
Node.prototype.setError = function (error, child) {
// ensure the dom exists
this.getDom();
this.error = error;
var tdError = this.dom.tdError;
if (error) {
if (!tdError) {
tdError = document.createElement('td');
this.dom.tdError = tdError;
this.dom.tdValue.parentNode.appendChild(tdError);
}
var popover = document.createElement('div');
popover.className = 'jsoneditor-popover jsoneditor-right';
popover.appendChild(document.createTextNode(error.message));
var button = document.createElement('button');
button.className = 'jsoneditor-schema-error';
button.appendChild(popover);
// update the direction of the popover
button.onmouseover = button.onfocus = function updateDirection() {
var directions = ['right', 'above', 'below', 'left'];
for (var i = 0; i < directions.length; i++) {
var direction = directions[i];
popover.className = 'jsoneditor-popover jsoneditor-' + direction;
var contentRect = this.editor.content.getBoundingClientRect();
var popoverRect = popover.getBoundingClientRect();
var margin = 20; // account for a scroll bar
var fit = util.insideRect(contentRect, popoverRect, margin);
if (fit) {
break;
}
}
}.bind(this);
// when clicking the error icon, expand all nodes towards the invalid
// child node, and set focus to the child node
if (child) {
button.onclick = function showInvalidNode() {
child.findParents().forEach(function (parent) {
parent.expand(false);
});
child.scrollTo(function () {
child.focus();
});
};
}
// apply the error message to the node
while (tdError.firstChild) {
tdError.removeChild(tdError.firstChild);
}
tdError.appendChild(button);
}
else {
if (tdError) {
this.dom.tdError.parentNode.removeChild(this.dom.tdError);
delete this.dom.tdError;
}
}
};
/**
* Get the index of this node: the index in the list of childs where this
* node is part of
* @return {number} Returns the index, or -1 if this is the root node
*/
Node.prototype.getIndex = function () {
return this.parent ? this.parent.childs.indexOf(this) : -1;
};
/**
* Set parent node
* @param {Node} parent
*/
Node.prototype.setParent = function(parent) {
this.parent = parent;
};
/**
* Set field
* @param {String} field
* @param {boolean} [fieldEditable]
*/
Node.prototype.setField = function(field, fieldEditable) {
this.field = field;
this.previousField = field;
this.fieldEditable = (fieldEditable === true);
};
/**
* Get field
* @return {String}
*/
Node.prototype.getField = function() {
if (this.field === undefined) {
this._getDomField();
}
return this.field;
};
/**
* Set value. Value is a JSON structure or an element String, Boolean, etc.
* @param {*} value
* @param {String} [type] Specify the type of the value. Can be 'auto',
* 'array', 'object', or 'string'
*/
Node.prototype.setValue = function(value, type) {
var childValue, child;
// first clear all current childs (if any)
var childs = this.childs;
if (childs) {
while (childs.length) {
this.removeChild(childs[0]);
}
}
// TODO: remove the DOM of this Node
this.type = this._getType(value);
// check if type corresponds with the provided type
if (type && type != this.type) {
if (type == 'string' && this.type == 'auto') {
this.type = type;
}
else {
throw new Error('Type mismatch: ' +
'cannot cast value of type "' + this.type +
' to the specified type "' + type + '"');
}
}
if (this.type == 'array') {
// array
this.childs = [];
for (var i = 0, iMax = value.length; i < iMax; i++) {
childValue = value[i];
if (childValue !== undefined && !(childValue instanceof Function)) {
// ignore undefined and functions
child = new Node(this.editor, {
value: childValue
});
this.appendChild(child);
}
}
this.value = '';
}
else if (this.type == 'object') {
// object
this.childs = [];
for (var childField in value) {
if (value.hasOwnProperty(childField)) {
childValue = value[childField];
if (childValue !== undefined && !(childValue instanceof Function)) {
// ignore undefined and functions
child = new Node(this.editor, {
field: childField,
value: childValue
});
this.appendChild(child);
}
}
}
this.value = '';
}
else {
// value
this.childs = undefined;
this.value = value;
/* TODO
if (typeof(value) == 'string') {
var escValue = JSON.stringify(value);
this.value = escValue.substring(1, escValue.length - 1);
console.log('check', value, this.value);
}
else {
this.value = value;
}
*/
}
this.previousValue = this.value;
};
/**
* Get value. Value is a JSON structure
* @return {*} value
*/
Node.prototype.getValue = function() {
//var childs, i, iMax;
if (this.type == 'array') {
var arr = [];
this.childs.forEach (function (child) {
arr.push(child.getValue());
});
return arr;
}
else if (this.type == 'object') {
var obj = {};
this.childs.forEach (function (child) {
obj[child.getField()] = child.getValue();
});
return obj;
}
else {
if (this.value === undefined) {
this._getDomValue();
}
return this.value;
}
};
/**
* Get the nesting level of this node
* @return {Number} level
*/
Node.prototype.getLevel = function() {
return (this.parent ? this.parent.getLevel() + 1 : 0);
};
/**
* Get path of the root node till the current node
* @return {Node[]} Returns an array with nodes
*/
Node.prototype.getPath = function() {
var path = this.parent ? this.parent.getPath() : [];
path.push(this);
return path;
};
/**
* Create a clone of a node
* The complete state of a clone is copied, including whether it is expanded or
* not. The DOM elements are not cloned.
* @return {Node} clone
*/
Node.prototype.clone = function() {
var clone = new Node(this.editor);
clone.type = this.type;
clone.field = this.field;
clone.fieldInnerText = this.fieldInnerText;
clone.fieldEditable = this.fieldEditable;
clone.value = this.value;
clone.valueInnerText = this.valueInnerText;
clone.expanded = this.expanded;
if (this.childs) {
// an object or array
var cloneChilds = [];
this.childs.forEach(function (child) {
var childClone = child.clone();
childClone.setParent(clone);
cloneChilds.push(childClone);
});
clone.childs = cloneChilds;
}
else {
// a value
clone.childs = undefined;
}
return clone;
};
/**
* Expand this node and optionally its childs.
* @param {boolean} [recurse] Optional recursion, true by default. When
* true, all childs will be expanded recursively
*/
Node.prototype.expand = function(recurse) {
if (!this.childs) {
return;
}
// set this node expanded
this.expanded = true;
if (this.dom.expand) {
this.dom.expand.className = 'jsoneditor-expanded';
}
this.showChilds();
if (recurse !== false) {
this.childs.forEach(function (child) {
child.expand(recurse);
});
}
};
/**
* Collapse this node and optionally its childs.
* @param {boolean} [recurse] Optional recursion, true by default. When
* true, all childs will be collapsed recursively
*/
Node.prototype.collapse = function(recurse) {
if (!this.childs) {
return;
}
this.hideChilds();
// collapse childs in case of recurse
if (recurse !== false) {
this.childs.forEach(function (child) {
child.collapse(recurse);
});
}
// make this node collapsed
if (this.dom.expand) {
this.dom.expand.className = 'jsoneditor-collapsed';
}
this.expanded = false;
};
/**
* Recursively show all childs when they are expanded
*/
Node.prototype.showChilds = function() {
var childs = this.childs;
if (!childs) {
return;
}
if (!this.expanded) {
return;
}
var tr = this.dom.tr;
var table = tr ? tr.parentNode : undefined;
if (table) {
// show row with append button
var append = this.getAppend();
var nextTr = tr.nextSibling;
if (nextTr) {
table.insertBefore(append, nextTr);
}
else {
table.appendChild(append);
}
// show childs
this.childs.forEach(function (child) {
table.insertBefore(child.getDom(), append);
child.showChilds();
});
}
};
/**
* Hide the node with all its childs
*/
Node.prototype.hide = function() {
var tr = this.dom.tr;
var table = tr ? tr.parentNode : undefined;
if (table) {
table.removeChild(tr);
}
this.hideChilds();
};
/**
* Recursively hide all childs
*/
Node.prototype.hideChilds = function() {
var childs = this.childs;
if (!childs) {
return;
}
if (!this.expanded) {
return;
}
// hide append row
var append = this.getAppend();
if (append.parentNode) {
append.parentNode.removeChild(append);
}
// hide childs
this.childs.forEach(function (child) {
child.hide();
});
};
/**
* Add a new child to the node.
* Only applicable when Node value is of type array or object
* @param {Node} node
*/
Node.prototype.appendChild = function(node) {
if (this._hasChilds()) {
// adjust the link to the parent
node.setParent(this);
node.fieldEditable = (this.type == 'object');
if (this.type == 'array') {
node.index = this.childs.length;
}
this.childs.push(node);
if (this.expanded) {
// insert into the DOM, before the appendRow
var newTr = node.getDom();
var appendTr = this.getAppend();
var table = appendTr ? appendTr.parentNode : undefined;
if (appendTr && table) {
table.insertBefore(newTr, appendTr);
}
node.showChilds();
}
this.updateDom({'updateIndexes': true});
node.updateDom({'recurse': true});
}
};
/**
* Move a node from its current parent to this node
* Only applicable when Node value is of type array or object
* @param {Node} node
* @param {Node} beforeNode
*/
Node.prototype.moveBefore = function(node, beforeNode) {
if (this._hasChilds()) {
// create a temporary row, to prevent the scroll position from jumping
// when removing the node
var tbody = (this.dom.tr) ? this.dom.tr.parentNode : undefined;
if (tbody) {
var trTemp = document.createElement('tr');
trTemp.style.height = tbody.clientHeight + 'px';
tbody.appendChild(trTemp);
}
if (node.parent) {
node.parent.removeChild(node);
}
if (beforeNode instanceof AppendNode) {
this.appendChild(node);
}
else {
this.insertBefore(node, beforeNode);
}
if (tbody) {
tbody.removeChild(trTemp);
}
}
};
/**
* Move a node from its current parent to this node
* Only applicable when Node value is of type array or object.
* If index is out of range, the node will be appended to the end
* @param {Node} node
* @param {Number} index
*/
Node.prototype.moveTo = function (node, index) {
if (node.parent == this) {
// same parent
var currentIndex = this.childs.indexOf(node);
if (currentIndex < index) {
// compensate the index for removal of the node itself
index++;
}
}
var beforeNode = this.childs[index] || this.append;
this.moveBefore(node, beforeNode);
};
/**
* Insert a new child before a given node
* Only applicable when Node value is of type array or object
* @param {Node} node
* @param {Node} beforeNode
*/
Node.prototype.insertBefore = function(node, beforeNode) {
if (this._hasChilds()) {
if (beforeNode == this.append) {
// append to the child nodes
// adjust the link to the parent
node.setParent(this);
node.fieldEditable = (this.type == 'object');
this.childs.push(node);
}
else {
// insert before a child node
var index = this.childs.indexOf(beforeNode);
if (index == -1) {
throw new Error('Node not found');
}
// adjust the link to the parent
node.setParent(this);
node.fieldEditable = (this.type == 'object');
this.childs.splice(index, 0, node);
}
if (this.expanded) {
// insert into the DOM
var newTr = node.getDom();
var nextTr = beforeNode.getDom();
var table = nextTr ? nextTr.parentNode : undefined;
if (nextTr && table) {
table.insertBefore(newTr, nextTr);
}
node.showChilds();
}
this.updateDom({'updateIndexes': true});
node.updateDom({'recurse': true});
}
};
/**
* Insert a new child before a given node
* Only applicable when Node value is of type array or object
* @param {Node} node
* @param {Node} afterNode
*/
Node.prototype.insertAfter = function(node, afterNode) {
if (this._hasChilds()) {
var index = this.childs.indexOf(afterNode);
var beforeNode = this.childs[index + 1];
if (beforeNode) {
this.insertBefore(node, beforeNode);
}
else {
this.appendChild(node);
}
}
};
/**
* Search in this node
* The node will be expanded when the text is found one of its childs, else
* it will be collapsed. Searches are case insensitive.
* @param {String} text
* @return {Node[]} results Array with nodes containing the search text
*/
Node.prototype.search = function(text) {
var results = [];
var index;
var search = text ? text.toLowerCase() : undefined;
// delete old search data
delete this.searchField;
delete this.searchValue;
// search in field
if (this.field != undefined) {
var field = String(this.field).toLowerCase();
index = field.indexOf(search);
if (index != -1) {
this.searchField = true;
results.push({
'node': this,
'elem': 'field'
});
}
// update dom
this._updateDomField();
}
// search in value
if (this._hasChilds()) {
// array, object
// search the nodes childs
if (this.childs) {
var childResults = [];
this.childs.forEach(function (child) {
childResults = childResults.concat(child.search(text));
});
results = results.concat(childResults);
}
// update dom
if (search != undefined) {
var recurse = false;
if (childResults.length == 0) {
this.collapse(recurse);
}
else {
this.expand(recurse);
}
}
}
else {
// string, auto
if (this.value != undefined ) {
var value = String(this.value).toLowerCase();
index = value.indexOf(search);
if (index != -1) {
this.searchValue = true;
results.push({
'node': this,
'elem': 'value'
});
}
}
// update dom
this._updateDomValue();
}
return results;
};
/**
* Move the scroll position such that this node is in the visible area.
* The node will not get the focus
* @param {function(boolean)} [callback]
*/
Node.prototype.scrollTo = function(callback) {
if (!this.dom.tr || !this.dom.tr.parentNode) {
// if the node is not visible, expand its parents
var parent = this.parent;
var recurse = false;
while (parent) {
parent.expand(recurse);
parent = parent.parent;
}
}
if (this.dom.tr && this.dom.tr.parentNode) {
this.editor.scrollTo(this.dom.tr.offsetTop, callback);
}
};
// stores the element name currently having the focus
Node.focusElement = undefined;
/**
* Set focus to this node
* @param {String} [elementName] The field name of the element to get the
* focus available values: 'drag', 'menu',
* 'expand', 'field', 'value' (default)
*/
Node.prototype.focus = function(elementName) {
Node.focusElement = elementName;
if (this.dom.tr && this.dom.tr.parentNode) {
var dom = this.dom;
switch (elementName) {
case 'drag':
if (dom.drag) {
dom.drag.focus();
}
else {
dom.menu.focus();
}
break;
case 'menu':
dom.menu.focus();
break;
case 'expand':
if (this._hasChilds()) {
dom.expand.focus();
}
else if (dom.field && this.fieldEditable) {
dom.field.focus();
util.selectContentEditable(dom.field);
}
else if (dom.value && !this._hasChilds()) {
dom.value.focus();
util.selectContentEditable(dom.value);
}
else {
dom.menu.focus();
}
break;
case 'field':
if (dom.field && this.fieldEditable) {
dom.field.focus();
util.selectContentEditable(dom.field);
}
else if (dom.value && !this._hasChilds()) {
dom.value.focus();
util.selectContentEditable(dom.value);
}
else if (this._hasChilds()) {
dom.expand.focus();
}
else {
dom.menu.focus();
}
break;
case 'value':
default:
if (dom.value && !this._hasChilds()) {
dom.value.focus();
util.selectContentEditable(dom.value);
}
else if (dom.field && this.fieldEditable) {
dom.field.focus();
util.selectContentEditable(dom.field);
}
else if (this._hasChilds()) {
dom.expand.focus();
}
else {
dom.menu.focus();
}
break;
}
}
};
/**
* Select all text in an editable div after a delay of 0 ms
* @param {Element} editableDiv
*/
Node.select = function(editableDiv) {
setTimeout(function () {
util.selectContentEditable(editableDiv);
}, 0);
};
/**
* Update the values from the DOM field and value of this node
*/
Node.prototype.blur = function() {
// retrieve the actual field and value from the DOM.
this._getDomValue(false);
this._getDomField(false);
};
/**
* Check if given node is a child. The method will check recursively to find
* this node.
* @param {Node} node
* @return {boolean} containsNode
*/
Node.prototype.containsNode = function(node) {
if (this == node) {
return true;
}
var childs = this.childs;
if (childs) {
// TODO: use the js5 Array.some() here?
for (var i = 0, iMax = childs.length; i < iMax; i++) {
if (childs[i].containsNode(node)) {
return true;
}
}
}
return false;
};
/**
* Move given node into this node
* @param {Node} node the childNode to be moved
* @param {Node} beforeNode node will be inserted before given
* node. If no beforeNode is given,
* the node is appended at the end
* @private
*/
Node.prototype._move = function(node, beforeNode) {
if (node == beforeNode) {
// nothing to do...
return;
}
// check if this node is not a child of the node to be moved here
if (node.containsNode(this)) {
throw new Error('Cannot move a field into a child of itself');
}
// remove the original node
if (node.parent) {
node.parent.removeChild(node);
}
// create a clone of the node
var clone = node.clone();
node.clearDom();
// insert or append the node
if (beforeNode) {
this.insertBefore(clone, beforeNode);
}
else {
this.appendChild(clone);
}
/* TODO: adjust the field name (to prevent equal field names)
if (this.type == 'object') {
}
*/
};
/**
* Remove a child from the node.
* Only applicable when Node value is of type array or object
* @param {Node} node The child node to be removed;
* @return {Node | undefined} node The removed node on success,
* else undefined
*/
Node.prototype.removeChild = function(node) {
if (this.childs) {
var index = this.childs.indexOf(node);
if (index != -1) {
node.hide();
// delete old search results
delete node.searchField;
delete node.searchValue;
var removedNode = this.childs.splice(index, 1)[0];
removedNode.parent = null;
this.updateDom({'updateIndexes': true});
return removedNode;
}
}
return undefined;
};
/**
* Remove a child node node from this node
* This method is equal to Node.removeChild, except that _remove fire an
* onChange event.
* @param {Node} node
* @private
*/
Node.prototype._remove = function (node) {
this.removeChild(node);
};
/**
* Change the type of the value of this Node
* @param {String} newType
*/
Node.prototype.changeType = function (newType) {
var oldType = this.type;
if (oldType == newType) {
// type is not changed
return;
}
if ((newType == 'string' || newType == 'auto') &&
(oldType == 'string' || oldType == 'auto')) {
// this is an easy change
this.type = newType;
}
else {
// change from array to object, or from string/auto to object/array
var table = this.dom.tr ? this.dom.tr.parentNode : undefined;
var lastTr;
if (this.expanded) {
lastTr = this.getAppend();
}
else {
lastTr = this.getDom();
}
var nextTr = (lastTr && lastTr.parentNode) ? lastTr.nextSibling : undefined;
// hide current field and all its childs
this.hide();
this.clearDom();
// adjust the field and the value
this.type = newType;
// adjust childs
if (newType == 'object') {
if (!this.childs) {
this.childs = [];
}
this.childs.forEach(function (child, index) {
child.clearDom();
delete child.index;
child.fieldEditable = true;
if (child.field == undefined) {
child.field = '';
}
});
if (oldType == 'string' || oldType == 'auto') {
this.expanded = true;
}
}
else if (newType == 'array') {
if (!this.childs) {
this.childs = [];
}
this.childs.forEach(function (child, index) {
child.clearDom();
child.fieldEditable = false;
child.index = index;
});
if (oldType == 'string' || oldType == 'auto') {
this.expanded = true;
}
}
else {
this.expanded = false;
}
// create new DOM
if (table) {
if (nextTr) {
table.insertBefore(this.getDom(), nextTr);
}
else {
table.appendChild(this.getDom());
}
}
this.showChilds();
}
if (newType == 'auto' || newType == 'string') {
// cast value to the correct type
if (newType == 'string') {
this.value = String(this.value);
}
else {
this.value = this._stringCast(String(this.value));
}
this.focus();
}
this.updateDom({'updateIndexes': true});
};
/**
* Retrieve value from DOM
* @param {boolean} [silent] If true (default), no errors will be thrown in
* case of invalid data
* @private
*/
Node.prototype._getDomValue = function(silent) {
if (this.dom.value && this.type != 'array' && this.type != 'object') {
this.valueInnerText = util.getInnerText(this.dom.value);
}
if (this.valueInnerText != undefined) {
try {
// retrieve the value
var value;
if (this.type == 'string') {
value = this._unescapeHTML(this.valueInnerText);
}
else {
var str = this._unescapeHTML(this.valueInnerText);
value = this._stringCast(str);
}
if (value !== this.value) {
this.value = value;
this._debouncedOnChangeValue();
}
}
catch (err) {
this.value = undefined;
// TODO: sent an action with the new, invalid value?
if (silent !== true) {
throw err;
}
}
}
};
/**
* Handle a changed value
* @private
*/
Node.prototype._onChangeValue = function () {
// get current selection, then override the range such that we can select
// the added/removed text on undo/redo
var oldSelection = this.editor.getSelection();
if (oldSelection.range) {
var undoDiff = util.textDiff(String(this.value), String(this.previousValue));
oldSelection.range.startOffset = undoDiff.start;
oldSelection.range.endOffset = undoDiff.end;
}
var newSelection = this.editor.getSelection();
if (newSelection.range) {
var redoDiff = util.textDiff(String(this.previousValue), String(this.value));
newSelection.range.startOffset = redoDiff.start;
newSelection.range.endOffset = redoDiff.end;
}
this.editor._onAction('editValue', {
node: this,
oldValue: this.previousValue,
newValue: this.value,
oldSelection: oldSelection,
newSelection: newSelection
});
this.previousValue = this.value;
};
/**
* Handle a changed field
* @private
*/
Node.prototype._onChangeField = function () {
// get current selection, then override the range such that we can select
// the added/removed text on undo/redo
var oldSelection = this.editor.getSelection();
if (oldSelection.range) {
var undoDiff = util.textDiff(this.field, this.previousField);
oldSelection.range.startOffset = undoDiff.start;
oldSelection.range.endOffset = undoDiff.end;
}
var newSelection = this.editor.getSelection();
if (newSelection.range) {
var redoDiff = util.textDiff(this.previousField, this.field);
newSelection.range.startOffset = redoDiff.start;
newSelection.range.endOffset = redoDiff.end;
}
this.editor._onAction('editField', {
node: this,
oldValue: this.previousField,
newValue: this.field,
oldSelection: oldSelection,
newSelection: newSelection
});
this.previousField = this.field;
};
/**
* Update dom value:
* - the text color of the value, depending on the type of the value
* - the height of the field, depending on the width
* - background color in case it is empty
* @private
*/
Node.prototype._updateDomValue = function () {
var domValue = this.dom.value;
if (domValue) {
var classNames = ['jsoneditor-value'];
// set text color depending on value type
var value = this.value;
var type = (this.type == 'auto') ? util.type(value) : this.type;
var isUrl = type == 'string' && util.isUrl(value);
classNames.push('jsoneditor-' + type);
if (isUrl) {
classNames.push('jsoneditor-url');
}
// visual styling when empty
var isEmpty = (String(this.value) == '' && this.type != 'array' && this.type != 'object');
if (isEmpty) {
classNames.push('jsoneditor-empty');
}
// highlight when there is a search result
if (this.searchValueActive) {
classNames.push('jsoneditor-highlight-active');
}
if (this.searchValue) {
classNames.push('jsoneditor-highlight');
}
domValue.className = classNames.join(' ');
// update title
if (type == 'array' || type == 'object') {
var count = this.childs ? this.childs.length : 0;
domValue.title = this.type + ' containing ' + count + ' items';
}
else if (isUrl && this.editable.value) {
domValue.title = 'Ctrl+Click or Ctrl+Enter to open url in new window';
}
else {
domValue.title = '';
}
// show checkbox when the value is a boolean
if (type === 'boolean' && this.editable.value) {
if (!this.dom.checkbox) {
this.dom.checkbox = document.createElement('input');
this.dom.checkbox.type = 'checkbox';
this.dom.tdCheckbox = document.createElement('td');
this.dom.tdCheckbox.className = 'jsoneditor-tree';
this.dom.tdCheckbox.appendChild(this.dom.checkbox);
this.dom.tdValue.parentNode.insertBefore(this.dom.tdCheckbox, this.dom.tdValue);
}
this.dom.checkbox.checked = this.value;
}
else {
// cleanup checkbox when displayed
if (this.dom.tdCheckbox) {
this.dom.tdCheckbox.parentNode.removeChild(this.dom.tdCheckbox);
delete this.dom.tdCheckbox;
delete this.dom.checkbox;
}
}
// strip formatting from the contents of the editable div
util.stripFormatting(domValue);
}
};
/**
* Update dom field:
* - the text color of the field, depending on the text
* - the height of the field, depending on the width
* - background color in case it is empty
* @private
*/
Node.prototype._updateDomField = function () {
var domField = this.dom.field;
if (domField) {
// make backgound color lightgray when empty
var isEmpty = (String(this.field) == '' && this.parent.type != 'array');
if (isEmpty) {
util.addClassName(domField, 'jsoneditor-empty');
}
else {
util.removeClassName(domField, 'jsoneditor-empty');
}
// highlight when there is a search result
if (this.searchFieldActive) {
util.addClassName(domField, 'jsoneditor-highlight-active');
}
else {
util.removeClassName(domField, 'jsoneditor-highlight-active');
}
if (this.searchField) {
util.addClassName(domField, 'jsoneditor-highlight');
}
else {
util.removeClassName(domField, 'jsoneditor-highlight');
}
// strip formatting from the contents of the editable div
util.stripFormatting(domField);
}
};
/**
* Retrieve field from DOM
* @param {boolean} [silent] If true (default), no errors will be thrown in
* case of invalid data
* @private
*/
Node.prototype._getDomField = function(silent) {
if (this.dom.field && this.fieldEditable) {
this.fieldInnerText = util.getInnerText(this.dom.field);
}
if (this.fieldInnerText != undefined) {
try {
var field = this._unescapeHTML(this.fieldInnerText);
if (field !== this.field) {
this.field = field;
this._debouncedOnChangeField();
}
}
catch (err) {
this.field = undefined;
// TODO: sent an action here, with the new, invalid value?
if (silent !== true) {
throw err;
}
}
}
};
/**
* Validate this node and all it's childs
* @return {Array.<{node: Node, error: {message: string}}>} Returns a list with duplicates
*/
Node.prototype.validate = function () {
var errors = [];
// find duplicate keys
if (this.type === 'object') {
var keys = {};
var duplicateKeys = [];
for (var i = 0; i < this.childs.length; i++) {
var child = this.childs[i];
if (keys[child.field]) {
duplicateKeys.push(child.field);
}
keys[child.field] = true;
}
if (duplicateKeys.length > 0) {
errors = this.childs
.filter(function (node) {
return duplicateKeys.indexOf(node.field) !== -1;
})
.map(function (node) {
return {
node: node,
error: {
message: 'duplicate key "' + node.field + '"'
}
}
});
}
}
// recurse over the childs
if (this.childs) {
for (var i = 0; i < this.childs.length; i++) {
var e = this.childs[i].validate();
if (e.length > 0) {
errors = errors.concat(e);
}
}
}
return errors;
};
/**
* Clear the dom of the node
*/
Node.prototype.clearDom = function() {
// TODO: hide the node first?
//this.hide();
// TODO: recursively clear dom?
this.dom = {};
};
/**
* Get the HTML DOM TR element of the node.
* The dom will be generated when not yet created
* @return {Element} tr HTML DOM TR Element
*/
Node.prototype.getDom = function() {
var dom = this.dom;
if (dom.tr) {
return dom.tr;
}
this._updateEditability();
// create row
dom.tr = document.createElement('tr');
dom.tr.node = this;
if (this.editor.options.mode === 'tree') { // note: we take here the global setting
var tdDrag = document.createElement('td');
if (this.editable.field) {
// create draggable area
if (this.parent) {
var domDrag = document.createElement('button');
dom.drag = domDrag;
domDrag.className = 'jsoneditor-dragarea';
domDrag.title = 'Drag to move this field (Alt+Shift+Arrows)';
tdDrag.appendChild(domDrag);
}
}
dom.tr.appendChild(tdDrag);
// create context menu
var tdMenu = document.createElement('td');
var menu = document.createElement('button');
dom.menu = menu;
menu.className = 'jsoneditor-contextmenu';
menu.title = 'Click to open the actions menu (Ctrl+M)';
tdMenu.appendChild(dom.menu);
dom.tr.appendChild(tdMenu);
}
// create tree and field
var tdField = document.createElement('td');
dom.tr.appendChild(tdField);
dom.tree = this._createDomTree();
tdField.appendChild(dom.tree);
this.updateDom({'updateIndexes': true});
return dom.tr;
};
/**
* DragStart event, fired on mousedown on the dragarea at the left side of a Node
* @param {Node[] | Node} nodes
* @param {Event} event
*/
Node.onDragStart = function (nodes, event) {
if (!Array.isArray(nodes)) {
return Node.onDragStart([nodes], event);
}
if (nodes.length === 0) {
return;
}
var firstNode = nodes[0];
var lastNode = nodes[nodes.length - 1];
var draggedNode = Node.getNodeFromTarget(event.target);
var beforeNode = lastNode._nextSibling();
var editor = firstNode.editor;
// in case of multiple selected nodes, offsetY prevents the selection from
// jumping when you start dragging one of the lower down nodes in the selection
var offsetY = util.getAbsoluteTop(draggedNode.dom.tr) - util.getAbsoluteTop(firstNode.dom.tr);
if (!editor.mousemove) {
editor.mousemove = util.addEventListener(window, 'mousemove', function (event) {
Node.onDrag(nodes, event);
});
}
if (!editor.mouseup) {
editor.mouseup = util.addEventListener(window, 'mouseup',function (event ) {
Node.onDragEnd(nodes, event);
});
}
editor.highlighter.lock();
editor.drag = {
oldCursor: document.body.style.cursor,
oldSelection: editor.getSelection(),
oldBeforeNode: beforeNode,
mouseX: event.pageX,
offsetY: offsetY,
level: firstNode.getLevel()
};
document.body.style.cursor = 'move';
event.preventDefault();
};
/**
* Drag event, fired when moving the mouse while dragging a Node
* @param {Node[] | Node} nodes
* @param {Event} event
*/
Node.onDrag = function (nodes, event) {
if (!Array.isArray(nodes)) {
return Node.onDrag([nodes], event);
}
if (nodes.length === 0) {
return;
}
// TODO: this method has grown too large. Split it in a number of methods
var editor = nodes[0].editor;
var mouseY = event.pageY - editor.drag.offsetY;
var mouseX = event.pageX;
var trThis, trPrev, trNext, trFirst, trLast, trRoot;
var nodePrev, nodeNext;
var topThis, topPrev, topFirst, heightThis, bottomNext, heightNext;
var moved = false;
// TODO: add an ESC option, which resets to the original position
// move up/down
var firstNode = nodes[0];
trThis = firstNode.dom.tr;
topThis = util.getAbsoluteTop(trThis);
heightThis = trThis.offsetHeight;
if (mouseY < topThis) {
// move up
trPrev = trThis;
do {
trPrev = trPrev.previousSibling;
nodePrev = Node.getNodeFromTarget(trPrev);
topPrev = trPrev ? util.getAbsoluteTop(trPrev) : 0;
}
while (trPrev && mouseY < topPrev);
if (nodePrev && !nodePrev.parent) {
nodePrev = undefined;
}
if (!nodePrev) {
// move to the first node
trRoot = trThis.parentNode.firstChild;
trPrev = trRoot ? trRoot.nextSibling : undefined;
nodePrev = Node.getNodeFromTarget(trPrev);
if (nodePrev == firstNode) {
nodePrev = undefined;
}
}
if (nodePrev) {
// check if mouseY is really inside the found node
trPrev = nodePrev.dom.tr;
topPrev = trPrev ? util.getAbsoluteTop(trPrev) : 0;
if (mouseY > topPrev + heightThis) {
nodePrev = undefined;
}
}
if (nodePrev) {
nodes.forEach(function (node) {
nodePrev.parent.moveBefore(node, nodePrev);
});
moved = true;
}
}
else {
// move down
var lastNode = nodes[nodes.length - 1];
trLast = (lastNode.expanded && lastNode.append) ? lastNode.append.getDom() : lastNode.dom.tr;
trFirst = trLast ? trLast.nextSibling : undefined;
if (trFirst) {
topFirst = util.getAbsoluteTop(trFirst);
trNext = trFirst;
do {
nodeNext = Node.getNodeFromTarget(trNext);
if (trNext) {
bottomNext = trNext.nextSibling ?
util.getAbsoluteTop(trNext.nextSibling) : 0;
heightNext = trNext ? (bottomNext - topFirst) : 0;
if (nodeNext.parent.childs.length == nodes.length &&
nodeNext.parent.childs[nodes.length - 1] == lastNode) {
// We are about to remove the last child of this parent,
// which will make the parents appendNode visible.
topThis += 27;
// TODO: dangerous to suppose the height of the appendNode a constant of 27 px.
}
}
trNext = trNext.nextSibling;
}
while (trNext && mouseY > topThis + heightNext);
if (nodeNext && nodeNext.parent) {
// calculate the desired level
var diffX = (mouseX - editor.drag.mouseX);
var diffLevel = Math.round(diffX / 24 / 2);
var level = editor.drag.level + diffLevel; // desired level
var levelNext = nodeNext.getLevel(); // level to be
// find the best fitting level (move upwards over the append nodes)
trPrev = nodeNext.dom.tr.previousSibling;
while (levelNext < level && trPrev) {
nodePrev = Node.getNodeFromTarget(trPrev);
var isDraggedNode = nodes.some(function (node) {
return node === nodePrev || nodePrev._isChildOf(node);
});
if (isDraggedNode) {
// neglect the dragged nodes themselves and their childs
}
else if (nodePrev instanceof AppendNode) {
var childs = nodePrev.parent.childs;
if (childs.length != nodes.length || childs[nodes.length - 1] != lastNode) {
// non-visible append node of a list of childs
// consisting of not only this node (else the
// append node will change into a visible "empty"
// text when removing this node).
nodeNext = Node.getNodeFromTarget(trPrev);
levelNext = nodeNext.getLevel();
}
else {
break;
}
}
else {
break;
}
trPrev = trPrev.previousSibling;
}
// move the node when its position is changed
if (trLast.nextSibling != nodeNext.dom.tr) {
nodes.forEach(function (node) {
nodeNext.parent.moveBefore(node, nodeNext);
});
moved = true;
}
}
}
}
if (moved) {
// update the dragging parameters when moved
editor.drag.mouseX = mouseX;
editor.drag.level = firstNode.getLevel();
}
// auto scroll when hovering around the top of the editor
editor.startAutoScroll(mouseY);
event.preventDefault();
};
/**
* Drag event, fired on mouseup after having dragged a node
* @param {Node[] | Node} nodes
* @param {Event} event
*/
Node.onDragEnd = function (nodes, event) {
if (!Array.isArray(nodes)) {
return Node.onDrag([nodes], event);
}
if (nodes.length === 0) {
return;
}
var firstNode = nodes[0];
var editor = firstNode.editor;
var parent = firstNode.parent;
var firstIndex = parent.childs.indexOf(firstNode);
var beforeNode = parent.childs[firstIndex + nodes.length] || parent.append;
// set focus to the context menu button of the first node
if (nodes[0]) {
nodes[0].dom.menu.focus();
}
var params = {
nodes: nodes,
oldSelection: editor.drag.oldSelection,
newSelection: editor.getSelection(),
oldBeforeNode: editor.drag.oldBeforeNode,
newBeforeNode: beforeNode
};
if (params.oldBeforeNode != params.newBeforeNode) {
// only register this action if the node is actually moved to another place
editor._onAction('moveNodes', params);
}
document.body.style.cursor = editor.drag.oldCursor;
editor.highlighter.unlock();
nodes.forEach(function (node) {
if (event.target !== node.dom.drag && event.target !== node.dom.menu) {
editor.highlighter.unhighlight();
}
});
delete editor.drag;
if (editor.mousemove) {
util.removeEventListener(window, 'mousemove', editor.mousemove);
delete editor.mousemove;
}
if (editor.mouseup) {
util.removeEventListener(window, 'mouseup', editor.mouseup);
delete editor.mouseup;
}
// Stop any running auto scroll
editor.stopAutoScroll();
event.preventDefault();
};
/**
* Test if this node is a child of an other node
* @param {Node} node
* @return {boolean} isChild
* @private
*/
Node.prototype._isChildOf = function (node) {
var n = this.parent;
while (n) {
if (n == node) {
return true;
}
n = n.parent;
}
return false;
};
/**
* Create an editable field
* @return {Element} domField
* @private
*/
Node.prototype._createDomField = function () {
return document.createElement('div');
};
/**
* Set highlighting for this node and all its childs.
* Only applied to the currently visible (expanded childs)
* @param {boolean} highlight
*/
Node.prototype.setHighlight = function (highlight) {
if (this.dom.tr) {
if (highlight) {
util.addClassName(this.dom.tr, 'jsoneditor-highlight');
}
else {
util.removeClassName(this.dom.tr, 'jsoneditor-highlight');
}
if (this.append) {
this.append.setHighlight(highlight);
}
if (this.childs) {
this.childs.forEach(function (child) {
child.setHighlight(highlight);
});
}
}
};
/**
* Select or deselect a node
* @param {boolean} selected
* @param {boolean} [isFirst]
*/
Node.prototype.setSelected = function (selected, isFirst) {
this.selected = selected;
if (this.dom.tr) {
if (selected) {
util.addClassName(this.dom.tr, 'jsoneditor-selected');
}
else {
util.removeClassName(this.dom.tr, 'jsoneditor-selected');
}
if (isFirst) {
util.addClassName(this.dom.tr, 'jsoneditor-first');
}
else {
util.removeClassName(this.dom.tr, 'jsoneditor-first');
}
if (this.append) {
this.append.setSelected(selected);
}
if (this.childs) {
this.childs.forEach(function (child) {
child.setSelected(selected);
});
}
}
};
/**
* Update the value of the node. Only primitive types are allowed, no Object
* or Array is allowed.
* @param {String | Number | Boolean | null} value
*/
Node.prototype.updateValue = function (value) {
this.value = value;
this.updateDom();
};
/**
* Update the field of the node.
* @param {String} field
*/
Node.prototype.updateField = function (field) {
this.field = field;
this.updateDom();
};
/**
* Update the HTML DOM, optionally recursing through the childs
* @param {Object} [options] Available parameters:
* {boolean} [recurse] If true, the
* DOM of the childs will be updated recursively.
* False by default.
* {boolean} [updateIndexes] If true, the childs
* indexes of the node will be updated too. False by
* default.
*/
Node.prototype.updateDom = function (options) {
// update level indentation
var domTree = this.dom.tree;
if (domTree) {
domTree.style.marginLeft = this.getLevel() * 24 + 'px';
}
// apply field to DOM
var domField = this.dom.field;
if (domField) {
if (this.fieldEditable) {
// parent is an object
domField.contentEditable = this.editable.field;
domField.spellcheck = false;
domField.className = 'jsoneditor-field';
}
else {
// parent is an array this is the root node
domField.className = 'jsoneditor-readonly';
}
var field;
if (this.index != undefined) {
field = this.index;
}
else if (this.field != undefined) {
field = this.field;
}
else if (this._hasChilds()) {
field = this.type;
}
else {
field = '';
}
domField.innerHTML = this._escapeHTML(field);
}
// apply value to DOM
var domValue = this.dom.value;
if (domValue) {
var count = this.childs ? this.childs.length : 0;
if (this.type == 'array') {
domValue.innerHTML = '[' + count + ']';
util.addClassName(this.dom.tr, 'jsoneditor-expandable');
}
else if (this.type == 'object') {
domValue.innerHTML = '{' + count + '}';
util.addClassName(this.dom.tr, 'jsoneditor-expandable');
}
else {
domValue.innerHTML = this._escapeHTML(this.value);
util.removeClassName(this.dom.tr, 'jsoneditor-expandable');
}
}
// update field and value
this._updateDomField();
this._updateDomValue();
// update childs indexes
if (options && options.updateIndexes === true) {
// updateIndexes is true or undefined
this._updateDomIndexes();
}
if (options && options.recurse === true) {
// recurse is true or undefined. update childs recursively
if (this.childs) {
this.childs.forEach(function (child) {
child.updateDom(options);
});
}
}
// update row with append button
if (this.append) {
this.append.updateDom();
}
};
/**
* Update the DOM of the childs of a node: update indexes and undefined field
* names.
* Only applicable when structure is an array or object
* @private
*/
Node.prototype._updateDomIndexes = function () {
var domValue = this.dom.value;
var childs = this.childs;
if (domValue && childs) {
if (this.type == 'array') {
childs.forEach(function (child, index) {
child.index = index;
var childField = child.dom.field;
if (childField) {
childField.innerHTML = index;
}
});
}
else if (this.type == 'object') {
childs.forEach(function (child) {
if (child.index != undefined) {
delete child.index;
if (child.field == undefined) {
child.field = '';
}
}
});
}
}
};
/**
* Create an editable value
* @private
*/
Node.prototype._createDomValue = function () {
var domValue;
if (this.type == 'array') {
domValue = document.createElement('div');
domValue.innerHTML = '[...]';
}
else if (this.type == 'object') {
domValue = document.createElement('div');
domValue.innerHTML = '{...}';
}
else {
if (!this.editable.value && util.isUrl(this.value)) {
// create a link in case of read-only editor and value containing an url
domValue = document.createElement('a');
domValue.href = this.value;
domValue.target = '_blank';
domValue.innerHTML = this._escapeHTML(this.value);
}
else {
// create an editable or read-only div
domValue = document.createElement('div');
domValue.contentEditable = this.editable.value;
domValue.spellcheck = false;
domValue.innerHTML = this._escapeHTML(this.value);
}
}
return domValue;
};
/**
* Create an expand/collapse button
* @return {Element} expand
* @private
*/
Node.prototype._createDomExpandButton = function () {
// create expand button
var expand = document.createElement('button');
if (this._hasChilds()) {
expand.className = this.expanded ? 'jsoneditor-expanded' : 'jsoneditor-collapsed';
expand.title =
'Click to expand/collapse this field (Ctrl+E). \n' +
'Ctrl+Click to expand/collapse including all childs.';
}
else {
expand.className = 'jsoneditor-invisible';
expand.title = '';
}
return expand;
};
/**
* Create a DOM tree element, containing the expand/collapse button
* @return {Element} domTree
* @private
*/
Node.prototype._createDomTree = function () {
var dom = this.dom;
var domTree = document.createElement('table');
var tbody = document.createElement('tbody');
domTree.style.borderCollapse = 'collapse'; // TODO: put in css
domTree.className = 'jsoneditor-values';
domTree.appendChild(tbody);
var tr = document.createElement('tr');
tbody.appendChild(tr);
// create expand button
var tdExpand = document.createElement('td');
tdExpand.className = 'jsoneditor-tree';
tr.appendChild(tdExpand);
dom.expand = this._createDomExpandButton();
tdExpand.appendChild(dom.expand);
dom.tdExpand = tdExpand;
// create the field
var tdField = document.createElement('td');
tdField.className = 'jsoneditor-tree';
tr.appendChild(tdField);
dom.field = this._createDomField();
tdField.appendChild(dom.field);
dom.tdField = tdField;
// create a separator
var tdSeparator = document.createElement('td');
tdSeparator.className = 'jsoneditor-tree';
tr.appendChild(tdSeparator);
if (this.type != 'object' && this.type != 'array') {
tdSeparator.appendChild(document.createTextNode(':'));
tdSeparator.className = 'jsoneditor-separator';
}
dom.tdSeparator = tdSeparator;
// create the value
var tdValue = document.createElement('td');
tdValue.className = 'jsoneditor-tree';
tr.appendChild(tdValue);
dom.value = this._createDomValue();
tdValue.appendChild(dom.value);
dom.tdValue = tdValue;
return domTree;
};
/**
* Handle an event. The event is caught centrally by the editor
* @param {Event} event
*/
Node.prototype.onEvent = function (event) {
var type = event.type,
target = event.target || event.srcElement,
dom = this.dom,
node = this,
focusNode,
expandable = this._hasChilds();
// check if mouse is on menu or on dragarea.
// If so, highlight current row and its childs
if (target == dom.drag || target == dom.menu) {
if (type == 'mouseover') {
this.editor.highlighter.highlight(this);
}
else if (type == 'mouseout') {
this.editor.highlighter.unhighlight();
}
}
// context menu events
if (type == 'click' && target == dom.menu) {
var highlighter = node.editor.highlighter;
highlighter.highlight(node);
highlighter.lock();
util.addClassName(dom.menu, 'jsoneditor-selected');
this.showContextMenu(dom.menu, function () {
util.removeClassName(dom.menu, 'jsoneditor-selected');
highlighter.unlock();
highlighter.unhighlight();
});
}
// expand events
if (type == 'click') {
if (target == dom.expand ||
((node.editor.options.mode === 'view' || node.editor.options.mode === 'form') && target.nodeName === 'DIV')) {
if (expandable) {
var recurse = event.ctrlKey; // with ctrl-key, expand/collapse all
this._onExpand(recurse);
}
}
}
// swap the value of a boolean when the checkbox displayed left is clicked
if (type == 'change' && target == dom.checkbox) {
this.dom.value.innerHTML = !this.value;
this._getDomValue();
}
// value events
var domValue = dom.value;
if (target == domValue) {
//noinspection FallthroughInSwitchStatementJS
switch (type) {
case 'focus':
focusNode = this;
break;
case 'blur':
case 'change':
this._getDomValue(true);
this._updateDomValue();
if (this.value) {
domValue.innerHTML = this._escapeHTML(this.value);
}
break;
case 'input':
//this._debouncedGetDomValue(true); // TODO
this._getDomValue(true);
this._updateDomValue();
break;
case 'keydown':
case 'mousedown':
// TODO: cleanup
this.editor.selection = this.editor.getSelection();
break;
case 'click':
if (event.ctrlKey || !this.editable.value) {
if (util.isUrl(this.value)) {
window.open(this.value, '_blank');
}
}
break;
case 'keyup':
//this._debouncedGetDomValue(true); // TODO
this._getDomValue(true);
this._updateDomValue();
break;
case 'cut':
case 'paste':
setTimeout(function () {
node._getDomValue(true);
node._updateDomValue();
}, 1);
break;
}
}
// field events
var domField = dom.field;
if (target == domField) {
switch (type) {
case 'focus':
focusNode = this;
break;
case 'blur':
case 'change':
this._getDomField(true);
this._updateDomField();
if (this.field) {
domField.innerHTML = this._escapeHTML(this.field);
}
break;
case 'input':
this._getDomField(true);
this._updateDomField();
break;
case 'keydown':
case 'mousedown':
this.editor.selection = this.editor.getSelection();
break;
case 'keyup':
this._getDomField(true);
this._updateDomField();
break;
case 'cut':
case 'paste':
setTimeout(function () {
node._getDomField(true);
node._updateDomField();
}, 1);
break;
}
}
// focus
// when clicked in whitespace left or right from the field or value, set focus
var domTree = dom.tree;
if (target == domTree.parentNode && type == 'click' && !event.hasMoved) {
var left = (event.offsetX != undefined) ?
(event.offsetX < (this.getLevel() + 1) * 24) :
(event.pageX < util.getAbsoluteLeft(dom.tdSeparator));// for FF
if (left || expandable) {
// node is expandable when it is an object or array
if (domField) {
util.setEndOfContentEditable(domField);
domField.focus();
}
}
else {
if (domValue) {
util.setEndOfContentEditable(domValue);
domValue.focus();
}
}
}
if (((target == dom.tdExpand && !expandable) || target == dom.tdField || target == dom.tdSeparator) &&
(type == 'click' && !event.hasMoved)) {
if (domField) {
util.setEndOfContentEditable(domField);
domField.focus();
}
}
if (type == 'keydown') {
this.onKeyDown(event);
}
};
/**
* Key down event handler
* @param {Event} event
*/
Node.prototype.onKeyDown = function (event) {
var keynum = event.which || event.keyCode;
var target = event.target || event.srcElement;
var ctrlKey = event.ctrlKey;
var shiftKey = event.shiftKey;
var altKey = event.altKey;
var handled = false;
var prevNode, nextNode, nextDom, nextDom2;
var editable = this.editor.options.mode === 'tree';
var oldSelection;
var oldBeforeNode;
var nodes;
var multiselection;
var selectedNodes = this.editor.multiselection.nodes.length > 0
? this.editor.multiselection.nodes
: [this];
var firstNode = selectedNodes[0];
var lastNode = selectedNodes[selectedNodes.length - 1];
// console.log(ctrlKey, keynum, event.charCode); // TODO: cleanup
if (keynum == 13) { // Enter
if (target == this.dom.value) {
if (!this.editable.value || event.ctrlKey) {
if (util.isUrl(this.value)) {
window.open(this.value, '_blank');
handled = true;
}
}
}
else if (target == this.dom.expand) {
var expandable = this._hasChilds();
if (expandable) {
var recurse = event.ctrlKey; // with ctrl-key, expand/collapse all
this._onExpand(recurse);
target.focus();
handled = true;
}
}
}
else if (keynum == 68) { // D
if (ctrlKey && editable) { // Ctrl+D
Node.onDuplicate(selectedNodes);
handled = true;
}
}
else if (keynum == 69) { // E
if (ctrlKey) { // Ctrl+E and Ctrl+Shift+E
this._onExpand(shiftKey); // recurse = shiftKey
target.focus(); // TODO: should restore focus in case of recursing expand (which takes DOM offline)
handled = true;
}
}
else if (keynum == 77 && editable) { // M
if (ctrlKey) { // Ctrl+M
this.showContextMenu(target);
handled = true;
}
}
else if (keynum == 46 && editable) { // Del
if (ctrlKey) { // Ctrl+Del
Node.onRemove(selectedNodes);
handled = true;
}
}
else if (keynum == 45 && editable) { // Ins
if (ctrlKey && !shiftKey) { // Ctrl+Ins
this._onInsertBefore();
handled = true;
}
else if (ctrlKey && shiftKey) { // Ctrl+Shift+Ins
this._onInsertAfter();
handled = true;
}
}
else if (keynum == 35) { // End
if (altKey) { // Alt+End
// find the last node
var endNode = this._lastNode();
if (endNode) {
endNode.focus(Node.focusElement || this._getElementName(target));
}
handled = true;
}
}
else if (keynum == 36) { // Home
if (altKey) { // Alt+Home
// find the first node
var homeNode = this._firstNode();
if (homeNode) {
homeNode.focus(Node.focusElement || this._getElementName(target));
}
handled = true;
}
}
else if (keynum == 37) { // Arrow Left
if (altKey && !shiftKey) { // Alt + Arrow Left
// move to left element
var prevElement = this._previousElement(target);
if (prevElement) {
this.focus(this._getElementName(prevElement));
}
handled = true;
}
else if (altKey && shiftKey && editable) { // Alt + Shift + Arrow left
if (lastNode.expanded) {
var appendDom = lastNode.getAppend();
nextDom = appendDom ? appendDom.nextSibling : undefined;
}
else {
var dom = lastNode.getDom();
nextDom = dom.nextSibling;
}
if (nextDom) {
nextNode = Node.getNodeFromTarget(nextDom);
nextDom2 = nextDom.nextSibling;
nextNode2 = Node.getNodeFromTarget(nextDom2);
if (nextNode && nextNode instanceof AppendNode &&
!(lastNode.parent.childs.length == 1) &&
nextNode2 && nextNode2.parent) {
oldSelection = this.editor.getSelection();
oldBeforeNode = lastNode._nextSibling();
selectedNodes.forEach(function (node) {
nextNode2.parent.moveBefore(node, nextNode2);
});
this.focus(Node.focusElement || this._getElementName(target));
this.editor._onAction('moveNodes', {
nodes: selectedNodes,
oldBeforeNode: oldBeforeNode,
newBeforeNode: nextNode2,
oldSelection: oldSelection,
newSelection: this.editor.getSelection()
});
}
}
}
}
else if (keynum == 38) { // Arrow Up
if (altKey && !shiftKey) { // Alt + Arrow Up
// find the previous node
prevNode = this._previousNode();
if (prevNode) {
this.editor.deselect(true);
prevNode.focus(Node.focusElement || this._getElementName(target));
}
handled = true;
}
else if (!altKey && ctrlKey && shiftKey && editable) { // Ctrl + Shift + Arrow Up
// select multiple nodes
prevNode = this._previousNode();
if (prevNode) {
multiselection = this.editor.multiselection;
multiselection.start = multiselection.start || this;
multiselection.end = prevNode;
nodes = this.editor._findTopLevelNodes(multiselection.start, multiselection.end);
this.editor.select(nodes);
prevNode.focus('field'); // select field as we know this always exists
}
handled = true;
}
else if (altKey && shiftKey && editable) { // Alt + Shift + Arrow Up
// find the previous node
prevNode = firstNode._previousNode();
if (prevNode && prevNode.parent) {
oldSelection = this.editor.getSelection();
oldBeforeNode = lastNode._nextSibling();
selectedNodes.forEach(function (node) {
prevNode.parent.moveBefore(node, prevNode);
});
this.focus(Node.focusElement || this._getElementName(target));
this.editor._onAction('moveNodes', {
nodes: selectedNodes,
oldBeforeNode: oldBeforeNode,
newBeforeNode: prevNode,
oldSelection: oldSelection,
newSelection: this.editor.getSelection()
});
}
handled = true;
}
}
else if (keynum == 39) { // Arrow Right
if (altKey && !shiftKey) { // Alt + Arrow Right
// move to right element
var nextElement = this._nextElement(target);
if (nextElement) {
this.focus(this._getElementName(nextElement));
}
handled = true;
}
else if (altKey && shiftKey && editable) { // Alt + Shift + Arrow Right
dom = firstNode.getDom();
var prevDom = dom.previousSibling;
if (prevDom) {
prevNode = Node.getNodeFromTarget(prevDom);
if (prevNode && prevNode.parent &&
(prevNode instanceof AppendNode)
&& !prevNode.isVisible()) {
oldSelection = this.editor.getSelection();
oldBeforeNode = lastNode._nextSibling();
selectedNodes.forEach(function (node) {
prevNode.parent.moveBefore(node, prevNode);
});
this.focus(Node.focusElement || this._getElementName(target));
this.editor._onAction('moveNodes', {
nodes: selectedNodes,
oldBeforeNode: oldBeforeNode,
newBeforeNode: prevNode,
oldSelection: oldSelection,
newSelection: this.editor.getSelection()
});
}
}
}
}
else if (keynum == 40) { // Arrow Down
if (altKey && !shiftKey) { // Alt + Arrow Down
// find the next node
nextNode = this._nextNode();
if (nextNode) {
this.editor.deselect(true);
nextNode.focus(Node.focusElement || this._getElementName(target));
}
handled = true;
}
else if (!altKey && ctrlKey && shiftKey && editable) { // Ctrl + Shift + Arrow Down
// select multiple nodes
nextNode = this._nextNode();
if (nextNode) {
multiselection = this.editor.multiselection;
multiselection.start = multiselection.start || this;
multiselection.end = nextNode;
nodes = this.editor._findTopLevelNodes(multiselection.start, multiselection.end);
this.editor.select(nodes);
nextNode.focus('field'); // select field as we know this always exists
}
handled = true;
}
else if (altKey && shiftKey && editable) { // Alt + Shift + Arrow Down
// find the 2nd next node and move before that one
if (lastNode.expanded) {
nextNode = lastNode.append ? lastNode.append._nextNode() : undefined;
}
else {
nextNode = lastNode._nextNode();
}
var nextNode2 = nextNode && (nextNode._nextNode() || nextNode.parent.append);
if (nextNode2 && nextNode2.parent) {
oldSelection = this.editor.getSelection();
oldBeforeNode = lastNode._nextSibling();
selectedNodes.forEach(function (node) {
nextNode2.parent.moveBefore(node, nextNode2);
});
this.focus(Node.focusElement || this._getElementName(target));
this.editor._onAction('moveNodes', {
nodes: selectedNodes,
oldBeforeNode: oldBeforeNode,
newBeforeNode: nextNode2,
oldSelection: oldSelection,
newSelection: this.editor.getSelection()
});
}
handled = true;
}
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
};
/**
* Handle the expand event, when clicked on the expand button
* @param {boolean} recurse If true, child nodes will be expanded too
* @private
*/
Node.prototype._onExpand = function (recurse) {
if (recurse) {
// Take the table offline
var table = this.dom.tr.parentNode; // TODO: not nice to access the main table like this
var frame = table.parentNode;
var scrollTop = frame.scrollTop;
frame.removeChild(table);
}
if (this.expanded) {
this.collapse(recurse);
}
else {
this.expand(recurse);
}
if (recurse) {
// Put the table online again
frame.appendChild(table);
frame.scrollTop = scrollTop;
}
};
/**
* Remove nodes
* @param {Node[] | Node} nodes
*/
Node.onRemove = function(nodes) {
if (!Array.isArray(nodes)) {
return Node.onRemove([nodes]);
}
if (nodes && nodes.length > 0) {
var firstNode = nodes[0];
var parent = firstNode.parent;
var editor = firstNode.editor;
var firstIndex = firstNode.getIndex();
editor.highlighter.unhighlight();
// adjust the focus
var oldSelection = editor.getSelection();
Node.blurNodes(nodes);
var newSelection = editor.getSelection();
// remove the nodes
nodes.forEach(function (node) {
node.parent._remove(node);
});
// store history action
editor._onAction('removeNodes', {
nodes: nodes.slice(0), // store a copy of the array!
parent: parent,
index: firstIndex,
oldSelection: oldSelection,
newSelection: newSelection
});
}
};
/**
* Duplicate nodes
* duplicated nodes will be added right after the original nodes
* @param {Node[] | Node} nodes
*/
Node.onDuplicate = function(nodes) {
if (!Array.isArray(nodes)) {
return Node.onDuplicate([nodes]);
}
if (nodes && nodes.length > 0) {
var lastNode = nodes[nodes.length - 1];
var parent = lastNode.parent;
var editor = lastNode.editor;
editor.deselect(editor.multiselection.nodes);
// duplicate the nodes
var oldSelection = editor.getSelection();
var afterNode = lastNode;
var clones = nodes.map(function (node) {
var clone = node.clone();
parent.insertAfter(clone, afterNode);
afterNode = clone;
return clone;
});
// set selection to the duplicated nodes
if (nodes.length === 1) {
clones[0].focus();
}
else {
editor.select(clones);
}
var newSelection = editor.getSelection();
editor._onAction('duplicateNodes', {
afterNode: lastNode,
nodes: clones,
parent: parent,
oldSelection: oldSelection,
newSelection: newSelection
});
}
};
/**
* Handle insert before event
* @param {String} [field]
* @param {*} [value]
* @param {String} [type] Can be 'auto', 'array', 'object', or 'string'
* @private
*/
Node.prototype._onInsertBefore = function (field, value, type) {
var oldSelection = this.editor.getSelection();
var newNode = new Node(this.editor, {
field: (field != undefined) ? field : '',
value: (value != undefined) ? value : '',
type: type
});
newNode.expand(true);
this.parent.insertBefore(newNode, this);
this.editor.highlighter.unhighlight();
newNode.focus('field');
var newSelection = this.editor.getSelection();
this.editor._onAction('insertBeforeNodes', {
nodes: [newNode],
beforeNode: this,
parent: this.parent,
oldSelection: oldSelection,
newSelection: newSelection
});
};
/**
* Handle insert after event
* @param {String} [field]
* @param {*} [value]
* @param {String} [type] Can be 'auto', 'array', 'object', or 'string'
* @private
*/
Node.prototype._onInsertAfter = function (field, value, type) {
var oldSelection = this.editor.getSelection();
var newNode = new Node(this.editor, {
field: (field != undefined) ? field : '',
value: (value != undefined) ? value : '',
type: type
});
newNode.expand(true);
this.parent.insertAfter(newNode, this);
this.editor.highlighter.unhighlight();
newNode.focus('field');
var newSelection = this.editor.getSelection();
this.editor._onAction('insertAfterNodes', {
nodes: [newNode],
afterNode: this,
parent: this.parent,
oldSelection: oldSelection,
newSelection: newSelection
});
};
/**
* Handle append event
* @param {String} [field]
* @param {*} [value]
* @param {String} [type] Can be 'auto', 'array', 'object', or 'string'
* @private
*/
Node.prototype._onAppend = function (field, value, type) {
var oldSelection = this.editor.getSelection();
var newNode = new Node(this.editor, {
field: (field != undefined) ? field : '',
value: (value != undefined) ? value : '',
type: type
});
newNode.expand(true);
this.parent.appendChild(newNode);
this.editor.highlighter.unhighlight();
newNode.focus('field');
var newSelection = this.editor.getSelection();
this.editor._onAction('appendNodes', {
nodes: [newNode],
parent: this.parent,
oldSelection: oldSelection,
newSelection: newSelection
});
};
/**
* Change the type of the node's value
* @param {String} newType
* @private
*/
Node.prototype._onChangeType = function (newType) {
var oldType = this.type;
if (newType != oldType) {
var oldSelection = this.editor.getSelection();
this.changeType(newType);
var newSelection = this.editor.getSelection();
this.editor._onAction('changeType', {
node: this,
oldType: oldType,
newType: newType,
oldSelection: oldSelection,
newSelection: newSelection
});
}
};
/**
* Sort the childs of the node. Only applicable when the node has type 'object'
* or 'array'.
* @param {String} direction Sorting direction. Available values: "asc", "desc"
* @private
*/
Node.prototype._onSort = function (direction) {
if (this._hasChilds()) {
var order = (direction == 'desc') ? -1 : 1;
var prop = (this.type == 'array') ? 'value': 'field';
this.hideChilds();
var oldChilds = this.childs;
var oldSort = this.sort;
// copy the array (the old one will be kept for an undo action
this.childs = this.childs.concat();
// sort the arrays
this.childs.sort(function (a, b) {
if (a[prop] > b[prop]) return order;
if (a[prop] < b[prop]) return -order;
return 0;
});
this.sort = (order == 1) ? 'asc' : 'desc';
this.editor._onAction('sort', {
node: this,
oldChilds: oldChilds,
oldSort: oldSort,
newChilds: this.childs,
newSort: this.sort
});
this.showChilds();
}
};
/**
* Create a table row with an append button.
* @return {HTMLElement | undefined} buttonAppend or undefined when inapplicable
*/
Node.prototype.getAppend = function () {
if (!this.append) {
this.append = new AppendNode(this.editor);
this.append.setParent(this);
}
return this.append.getDom();
};
/**
* Find the node from an event target
* @param {Node} target
* @return {Node | undefined} node or undefined when not found
* @static
*/
Node.getNodeFromTarget = function (target) {
while (target) {
if (target.node) {
return target.node;
}
target = target.parentNode;
}
return undefined;
};
/**
* Remove the focus of given nodes, and move the focus to the (a) node before,
* (b) the node after, or (c) the parent node.
* @param {Array.<Node> | Node} nodes
*/
Node.blurNodes = function (nodes) {
if (!Array.isArray(nodes)) {
Node.blurNodes([nodes]);
return;
}
var firstNode = nodes[0];
var parent = firstNode.parent;
var firstIndex = firstNode.getIndex();
if (parent.childs[firstIndex + nodes.length]) {
parent.childs[firstIndex + nodes.length].focus();
}
else if (parent.childs[firstIndex - 1]) {
parent.childs[firstIndex - 1].focus();
}
else {
parent.focus();
}
};
/**
* Get the next sibling of current node
* @return {Node} nextSibling
* @private
*/
Node.prototype._nextSibling = function () {
var index = this.parent.childs.indexOf(this);
return this.parent.childs[index + 1] || this.parent.append;
};
/**
* Get the previously rendered node
* @return {Node | null} previousNode
* @private
*/
Node.prototype._previousNode = function () {
var prevNode = null;
var dom = this.getDom();
if (dom && dom.parentNode) {
// find the previous field
var prevDom = dom;
do {
prevDom = prevDom.previousSibling;
prevNode = Node.getNodeFromTarget(prevDom);
}
while (prevDom && (prevNode instanceof AppendNode && !prevNode.isVisible()));
}
return prevNode;
};
/**
* Get the next rendered node
* @return {Node | null} nextNode
* @private
*/
Node.prototype._nextNode = function () {
var nextNode = null;
var dom = this.getDom();
if (dom && dom.parentNode) {
// find the previous field
var nextDom = dom;
do {
nextDom = nextDom.nextSibling;
nextNode = Node.getNodeFromTarget(nextDom);
}
while (nextDom && (nextNode instanceof AppendNode && !nextNode.isVisible()));
}
return nextNode;
};
/**
* Get the first rendered node
* @return {Node | null} firstNode
* @private
*/
Node.prototype._firstNode = function () {
var firstNode = null;
var dom = this.getDom();
if (dom && dom.parentNode) {
var firstDom = dom.parentNode.firstChild;
firstNode = Node.getNodeFromTarget(firstDom);
}
return firstNode;
};
/**
* Get the last rendered node
* @return {Node | null} lastNode
* @private
*/
Node.prototype._lastNode = function () {
var lastNode = null;
var dom = this.getDom();
if (dom && dom.parentNode) {
var lastDom = dom.parentNode.lastChild;
lastNode = Node.getNodeFromTarget(lastDom);
while (lastDom && (lastNode instanceof AppendNode && !lastNode.isVisible())) {
lastDom = lastDom.previousSibling;
lastNode = Node.getNodeFromTarget(lastDom);
}
}
return lastNode;
};
/**
* Get the next element which can have focus.
* @param {Element} elem
* @return {Element | null} nextElem
* @private
*/
Node.prototype._previousElement = function (elem) {
var dom = this.dom;
// noinspection FallthroughInSwitchStatementJS
switch (elem) {
case dom.value:
if (this.fieldEditable) {
return dom.field;
}
// intentional fall through
case dom.field:
if (this._hasChilds()) {
return dom.expand;
}
// intentional fall through
case dom.expand:
return dom.menu;
case dom.menu:
if (dom.drag) {
return dom.drag;
}
// intentional fall through
default:
return null;
}
};
/**
* Get the next element which can have focus.
* @param {Element} elem
* @return {Element | null} nextElem
* @private
*/
Node.prototype._nextElement = function (elem) {
var dom = this.dom;
// noinspection FallthroughInSwitchStatementJS
switch (elem) {
case dom.drag:
return dom.menu;
case dom.menu:
if (this._hasChilds()) {
return dom.expand;
}
// intentional fall through
case dom.expand:
if (this.fieldEditable) {
return dom.field;
}
// intentional fall through
case dom.field:
if (!this._hasChilds()) {
return dom.value;
}
default:
return null;
}
};
/**
* Get the dom name of given element. returns null if not found.
* For example when element == dom.field, "field" is returned.
* @param {Element} element
* @return {String | null} elementName Available elements with name: 'drag',
* 'menu', 'expand', 'field', 'value'
* @private
*/
Node.prototype._getElementName = function (element) {
var dom = this.dom;
for (var name in dom) {
if (dom.hasOwnProperty(name)) {
if (dom[name] == element) {
return name;
}
}
}
return null;
};
/**
* Test if this node has childs. This is the case when the node is an object
* or array.
* @return {boolean} hasChilds
* @private
*/
Node.prototype._hasChilds = function () {
return this.type == 'array' || this.type == 'object';
};
// titles with explanation for the different types
Node.TYPE_TITLES = {
'auto': 'Field type "auto". ' +
'The field type is automatically determined from the value ' +
'and can be a string, number, boolean, or null.',
'object': 'Field type "object". ' +
'An object contains an unordered set of key/value pairs.',
'array': 'Field type "array". ' +
'An array contains an ordered collection of values.',
'string': 'Field type "string". ' +
'Field type is not determined from the value, ' +
'but always returned as string.'
};
/**
* Show a contextmenu for this node
* @param {HTMLElement} anchor Anchor element to attach the context menu to
* as sibling.
* @param {function} [onClose] Callback method called when the context menu
* is being closed.
*/
Node.prototype.showContextMenu = function (anchor, onClose) {
var node = this;
var titles = Node.TYPE_TITLES;
var items = [];
if (this.editable.value) {
items.push({
text: 'Type',
title: 'Change the type of this field',
className: 'jsoneditor-type-' + this.type,
submenu: [
{
text: 'Auto',
className: 'jsoneditor-type-auto' +
(this.type == 'auto' ? ' jsoneditor-selected' : ''),
title: titles.auto,
click: function () {
node._onChangeType('auto');
}
},
{
text: 'Array',
className: 'jsoneditor-type-array' +
(this.type == 'array' ? ' jsoneditor-selected' : ''),
title: titles.array,
click: function () {
node._onChangeType('array');
}
},
{
text: 'Object',
className: 'jsoneditor-type-object' +
(this.type == 'object' ? ' jsoneditor-selected' : ''),
title: titles.object,
click: function () {
node._onChangeType('object');
}
},
{
text: 'String',
className: 'jsoneditor-type-string' +
(this.type == 'string' ? ' jsoneditor-selected' : ''),
title: titles.string,
click: function () {
node._onChangeType('string');
}
}
]
});
}
if (this._hasChilds()) {
var direction = ((this.sort == 'asc') ? 'desc': 'asc');
items.push({
text: 'Sort',
title: 'Sort the childs of this ' + this.type,
className: 'jsoneditor-sort-' + direction,
click: function () {
node._onSort(direction);
},
submenu: [
{
text: 'Ascending',
className: 'jsoneditor-sort-asc',
title: 'Sort the childs of this ' + this.type + ' in ascending order',
click: function () {
node._onSort('asc');
}
},
{
text: 'Descending',
className: 'jsoneditor-sort-desc',
title: 'Sort the childs of this ' + this.type +' in descending order',
click: function () {
node._onSort('desc');
}
}
]
});
}
if (this.parent && this.parent._hasChilds()) {
if (items.length) {
// create a separator
items.push({
'type': 'separator'
});
}
// create append button (for last child node only)
var childs = node.parent.childs;
if (node == childs[childs.length - 1]) {
items.push({
text: 'Append',
title: 'Append a new field with type \'auto\' after this field (Ctrl+Shift+Ins)',
submenuTitle: 'Select the type of the field to be appended',
className: 'jsoneditor-append',
click: function () {
node._onAppend('', '', 'auto');
},
submenu: [
{
text: 'Auto',
className: 'jsoneditor-type-auto',
title: titles.auto,
click: function () {
node._onAppend('', '', 'auto');
}
},
{
text: 'Array',
className: 'jsoneditor-type-array',
title: titles.array,
click: function () {
node._onAppend('', []);
}
},
{
text: 'Object',
className: 'jsoneditor-type-object',
title: titles.object,
click: function () {
node._onAppend('', {});
}
},
{
text: 'String',
className: 'jsoneditor-type-string',
title: titles.string,
click: function () {
node._onAppend('', '', 'string');
}
}
]
});
}
// create insert button
items.push({
text: 'Insert',
title: 'Insert a new field with type \'auto\' before this field (Ctrl+Ins)',
submenuTitle: 'Select the type of the field to be inserted',
className: 'jsoneditor-insert',
click: function () {
node._onInsertBefore('', '', 'auto');
},
submenu: [
{
text: 'Auto',
className: 'jsoneditor-type-auto',
title: titles.auto,
click: function () {
node._onInsertBefore('', '', 'auto');
}
},
{
text: 'Array',
className: 'jsoneditor-type-array',
title: titles.array,
click: function () {
node._onInsertBefore('', []);
}
},
{
text: 'Object',
className: 'jsoneditor-type-object',
title: titles.object,
click: function () {
node._onInsertBefore('', {});
}
},
{
text: 'String',
className: 'jsoneditor-type-string',
title: titles.string,
click: function () {
node._onInsertBefore('', '', 'string');
}
}
]
});
if (this.editable.field) {
// create duplicate button
items.push({
text: 'Duplicate',
title: 'Duplicate this field (Ctrl+D)',
className: 'jsoneditor-duplicate',
click: function () {
Node.onDuplicate(node);
}
});
// create remove button
items.push({
text: 'Remove',
title: 'Remove this field (Ctrl+Del)',
className: 'jsoneditor-remove',
click: function () {
Node.onRemove(node);
}
});
}
}
var menu = new ContextMenu(items, {close: onClose});
menu.show(anchor, this.editor.content);
};
/**
* get the type of a value
* @param {*} value
* @return {String} type Can be 'object', 'array', 'string', 'auto'
* @private
*/
Node.prototype._getType = function(value) {
if (value instanceof Array) {
return 'array';
}
if (value instanceof Object) {
return 'object';
}
if (typeof(value) == 'string' && typeof(this._stringCast(value)) != 'string') {
return 'string';
}
return 'auto';
};
/**
* cast contents of a string to the correct type. This can be a string,
* a number, a boolean, etc
* @param {String} str
* @return {*} castedStr
* @private
*/
Node.prototype._stringCast = function(str) {
var lower = str.toLowerCase(),
num = Number(str), // will nicely fail with '123ab'
numFloat = parseFloat(str); // will nicely fail with ' '
if (str == '') {
return '';
}
else if (lower == 'null') {
return null;
}
else if (lower == 'true') {
return true;
}
else if (lower == 'false') {
return false;
}
else if (!isNaN(num) && !isNaN(numFloat)) {
return num;
}
else {
return str;
}
};
/**
* escape a text, such that it can be displayed safely in an HTML element
* @param {String} text
* @return {String} escapedText
* @private
*/
Node.prototype._escapeHTML = function (text) {
if (typeof text !== 'string') {
return String(text);
}
else {
var htmlEscaped = String(text)
.replace(/&/g, '&') // must be replaced first!
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ /g, ' ') // replace double space with an nbsp and space
.replace(/^ /, ' ') // space at start
.replace(/ $/, ' '); // space at end
var json = JSON.stringify(htmlEscaped);
var html = json.substring(1, json.length - 1);
if (this.editor.options.escapeUnicode === true) {
html = util.escapeUnicodeChars(html);
}
return html;
}
};
/**
* unescape a string.
* @param {String} escapedText
* @return {String} text
* @private
*/
Node.prototype._unescapeHTML = function (escapedText) {
var json = '"' + this._escapeJSON(escapedText) + '"';
var htmlEscaped = util.parse(json);
return htmlEscaped
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ |\u00A0/g, ' ')
.replace(/&/g, '&'); // must be replaced last
};
/**
* escape a text to make it a valid JSON string. The method will:
* - replace unescaped double quotes with '\"'
* - replace unescaped backslash with '\\'
* - replace returns with '\n'
* @param {String} text
* @return {String} escapedText
* @private
*/
Node.prototype._escapeJSON = function (text) {
// TODO: replace with some smart regex (only when a new solution is faster!)
var escaped = '';
var i = 0;
while (i < text.length) {
var c = text.charAt(i);
if (c == '\n') {
escaped += '\\n';
}
else if (c == '\\') {
escaped += c;
i++;
c = text.charAt(i);
if (c === '' || '"\\/bfnrtu'.indexOf(c) == -1) {
escaped += '\\'; // no valid escape character
}
escaped += c;
}
else if (c == '"') {
escaped += '\\"';
}
else {
escaped += c;
}
i++;
}
return escaped;
};
// TODO: find a nicer solution to resolve this circular dependency between Node and AppendNode
var AppendNode = appendNodeFactory(Node);
module.exports = Node;
| Elastic-Hub/elastic-hub | static-site/libs/jsoneditor/src/js/Node.js | JavaScript | mit | 89,693 |
(function(global){
function Rye (selector, context) {
if (!(this instanceof Rye)){
return new Rye(selector, context)
}
if (selector instanceof Rye){
return selector
}
var util = Rye.require('Util')
if (typeof selector === 'string') {
this.selector = selector
this.elements = this.qsa(context, selector)
} else if (selector instanceof Array) {
this.elements = util.unique(selector.filter(util.isElement))
} else if (util.isNodeList(selector)) {
this.elements = Array.prototype.slice.call(selector).filter(util.isElement)
} else if (util.isElement(selector)) {
this.elements = [selector]
} else {
this.elements = []
}
this._update()
}
Rye.version = '0.1.0'
// Minimalist module system
var modules = {}
Rye.require = function (module) {
return modules[module]
}
Rye.define = function (module, fn) {
modules[module] = fn.call(Rye.prototype)
}
// Export global object
global.Rye = Rye
})(window)
;Rye.define('Util', function(){
var _slice = Array.prototype.slice
, _forEach = Array.prototype.forEach
, _toString = Object.prototype.toString
var uid = {
current: 0
, next: function(){ return ++this.current }
}
function each (obj, fn, context) {
if (!obj) {
return
}
if (obj.forEach === _forEach) {
return obj.forEach(fn, context)
}
if (obj.length === +obj.length) {
for (var i = 0; i < obj.length; i++) {
fn.call(context || obj, obj[i], i, obj)
}
} else {
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
fn.call(context || obj, obj[key], key, obj)
}
}
}
function extend (obj) {
each(_slice.call(arguments, 1), function(source){
each(source, function(value, key){
obj[key] = value
})
})
return obj
}
function inherits (child, parent) {
extend(child, parent)
function Ctor () {
this.constructor = child
}
Ctor.prototype = parent.prototype
child.prototype = new Ctor()
child.__super__ = parent.prototype
return child
}
function isElement (element) {
return element && (element.nodeType === 1 || element.nodeType === 9)
}
function isNodeList (obj) {
return obj && is(['nodelist', 'htmlcollection', 'htmlformcontrolscollection'], obj)
}
function unique (array) {
return array.filter(function(item, idx){
return array.indexOf(item) == idx
})
}
function pluck (array, property) {
return array.map(function(item){
return item[property]
})
}
function put (array, property, value) {
return array.forEach(function(item, i){
array[i][property] = value
})
}
function prefix (key, obj) {
var result
, upcased = key[0].toUpperCase() + key.substring(1)
, prefixes = ['moz', 'webkit', 'ms', 'o']
obj = obj || window
if (result = obj[key]){
return result
}
// No pretty array methods here :(
// http://jsperf.com/everywhile
while(prefix = prefixes.shift()){
if (result = obj[prefix + upcased]){
break;
}
}
return result
}
function _apply (context, fn, applyArgs, cutoff, fromLeft) {
if (typeof fn === 'string') {
fn = context[fn]
}
return function () {
var args = _slice.call(arguments, 0, cutoff || Infinity)
if (applyArgs) {
args = fromLeft ? applyArgs.concat(args) : args.concat(applyArgs)
}
if (typeof context === 'number') {
context = args[context]
}
return fn.apply(context || this, args)
}
}
function applyRight (context, fn, applyArgs, cutoff) {
return _apply(context, fn, applyArgs, cutoff)
}
function applyLeft (context, fn, applyArgs, cutoff) {
return _apply(context, fn, applyArgs, cutoff, true)
}
function curry (fn) {
return applyLeft(this, fn, _slice.call(arguments, 1))
}
function getUid (element) {
return element.rye_id || (element.rye_id = uid.next())
}
function type (obj) {
var ref = _toString.call(obj).match(/\s(\w+)\]$/)
return ref && ref[1].toLowerCase()
}
function is (kind, obj) {
return kind.indexOf(type(obj)) >= 0
}
return {
each : each
, extend : extend
, inherits : inherits
, isElement : isElement
, isNodeList : isNodeList
, unique : unique
, pluck : pluck
, put : put
, prefix : prefix
, applyRight : applyRight
, applyLeft : applyLeft
, curry : curry
, getUid : getUid
, type : type
, is : is
}
})
;Rye.define('Data', function(){
var util = Rye.require('Util')
, data = {}
function set (element, key, value) {
var id = util.getUid(element)
, obj = data[id] || (data[id] = {})
obj[key] = value
}
function get (element, key) {
var obj = data[util.getUid(element)]
if (key == null) {
return obj
}
return obj && obj[key]
}
this.data = function (key, value) {
if (value !== undefined) {
this.each(function(element){
set(element, key, value)
})
return this
}
if (this.elements.length === 1) {
return get(this.elements[0], key)
} else {
return this.elements.map(function(element){
return get(element, key)
})
}
}
return {
set : set
, get : get
}
})
;Rye.define('Query', function(){
var util = Rye.require('Util')
, _slice = Array.prototype.slice
, selectorRE = /^([.#]?)([\w\-]+)$/
, selectorType = {
'.': 'getElementsByClassName'
, '#': 'getElementById'
, '' : 'getElementsByTagName'
, '_': 'querySelectorAll'
}
, dummyDiv = document.createElement('div')
function matches(element, selector) {
var matchesSelector, match
if (!element || !util.isElement(element) || !selector) {
return false
}
if (selector.nodeType) {
return element === selector
}
if (selector instanceof Rye) {
return selector.elements.some(function(selector){
return matches(element, selector)
})
}
if (element === document) {
return false
}
matchesSelector = util.prefix('matchesSelector', dummyDiv)
if (matchesSelector) {
return matchesSelector.call(element, selector)
}
// fall back to performing a selector:
if (!element.parentNode) {
dummyDiv.appendChild(element)
}
match = qsa(element.parentNode, selector).indexOf(element) >= 0
if (element.parentNode === dummyDiv) {
dummyDiv.removeChild(element)
}
return match
}
function qsa (element, selector) {
var method
element = element || document
// http://jsperf.com/getelementbyid-vs-queryselector/11
if (!selector.match(selectorRE) || (RegExp.$1 === '#' && element !== document)) {
method = selectorType._
} else {
method = selectorType[RegExp.$1]
selector = RegExp.$2
}
var result = element[method](selector)
if (util.isNodeList(result)){
return _slice.call(result)
}
if (util.isElement(result)){
return [result]
}
return []
}
// Walks the DOM tree using `method`, returns
// when an element node is found
function getClosestNode (element, method, selector) {
do {
element = element[method]
} while (element && ((selector && !matches(element, selector)) || !util.isElement(element)))
return element
}
// Creates a new Rye instance applying a filter if necessary
function _create (elements, selector) {
return selector == null ? new Rye(elements) : new Rye(elements).filter(selector)
}
this.qsa = qsa
this.find = function (selector) {
var elements
if (this.length === 1) {
elements = qsa(this.elements[0], selector)
} else {
elements = this.elements.reduce(function(elements, element){
return elements.concat(qsa(element, selector))
}, [])
}
return _create(elements)
}
this.filter = function (selector, inverse) {
if (typeof selector === 'function') {
var fn = selector
return _create(this.elements.filter(function(element, index){
return fn.call(element, element, index) != (inverse || false)
}))
}
if (selector && selector[0] === '!') {
selector = selector.substr(1)
inverse = true
}
return _create(this.elements.filter(function(element){
return matches(element, selector) != (inverse || false)
}))
}
this.contains = function (selector) {
var matches
return _create(this.elements.reduce(function(elements, element){
matches = qsa(element, selector)
return elements.concat(matches.length ? element : null)
}, []))
}
this.is = function (selector) {
return this.length > 0 && this.filter(selector).length > 0
}
this.not = function (selector) {
return this.filter(selector, true)
}
this.index = function (selector) {
if (selector == null) {
return this.parent().children().indexOf(this.elements[0])
}
return this.indexOf(new Rye(selector).elements[0])
}
this.add = function (selector, context) {
var elements = selector
if (typeof selector === 'string') {
elements = new Rye(selector, context).elements
}
return this.concat(elements)
}
// Extract a list with the provided property for each value.
// This works like underscore's pluck, with the added
// getClosestNode() method to avoid picking up non-html nodes.
this.pluckNode = function (property) {
return this.map(function(element){
return getClosestNode(element, property)
})
}
this.next = function () {
return _create(this.pluckNode('nextSibling'))
}
this.prev = function () {
return _create(this.pluckNode('previousSibling'))
}
this.first = function () {
return _create(this.get(0))
}
this.last = function () {
return _create(this.get(-1))
}
this.siblings = function (selector) {
var siblings = []
this.each(function(element){
_slice.call(element.parentNode.childNodes).forEach(function(child){
if (util.isElement(child) && child !== element){
siblings.push(child)
}
})
})
return _create(siblings, selector)
}
this.parent = function (selector) {
return _create(this.pluck('parentNode'), selector)
}
// borrow from zepto
this.parents = function (selector) {
var ancestors = []
, elements = this.elements
, fn = function (element) {
if ((element = element.parentNode) && element !== document && ancestors.indexOf(element) < 0) {
ancestors.push(element)
return element
}
}
while (elements.length > 0 && elements[0] !== undefined) {
elements = elements.map(fn)
}
return _create(ancestors, selector)
}
this.closest = function (selector) {
return this.map(function(element){
if (matches(element, selector)) {
return element
}
return getClosestNode(element, 'parentNode', selector)
})
}
this.children = function (selector) {
return _create(this.elements.reduce(function(elements, element){
var childrens = _slice.call(element.children)
return elements.concat(childrens)
}, []), selector)
}
return {
matches : matches
, qsa : qsa
, getClosestNode : getClosestNode
}
})
;Rye.define('Collection', function(){
var util = Rye.require('Util')
, _slice = Array.prototype.slice
, _concat = Array.prototype.concat
this.get = function (index) {
if (index == null) {
return this.elements.slice()
}
return this.elements[index < 0 ? this.elements.length + index : index]
}
this.eq = function (index) {
// We have to explicitly null the selection since .get()
// returns the whole collection when called without arguments.
if (index == null) {
return new Rye()
}
return new Rye(this.get(index))
}
// Methods that return a usable value
;['forEach', 'reduce', 'reduceRight', 'indexOf'].forEach(function(method){
this[method] = function (a, b, c, d) {
return this.elements[method](a, b, c, d)
}
}.bind(this))
// Methods that return a list are turned into a Rye instance
;['map', 'sort'].forEach(function(method){
this[method] = function (a, b, c, d) {
return new Rye(this.elements[method](a, b, c, d))
}
}.bind(this))
this.each = function (fn) {
this.elements.forEach(fn)
return this
}
this.iterate = function(method, context){
return function(a, b, c, d){
return this.each(function(element){
method.call(context, element, a, b, c, d)
})
}
}
this.push = function (item) {
if (util.isElement(item)){
this.elements.push(item)
this._update()
return this.length - 1
} else {
return -1
}
}
this.slice = function (start, end) {
return new Rye(_slice.call(this.elements, start, end))
}
// Concatenate two elements lists, do .unique() clean-up
this.concat = function () {
var args = _slice.call(arguments).map(function(arr){
return arr instanceof Rye ? arr.elements : arr
})
return new Rye(_concat.apply(this.elements, args))
}
this.pluck = function (property) {
return util.pluck(this.elements, property)
}
this.put = function (property, value) {
util.put(this.elements, property, value)
return this
}
this._update = function () {
this.length = this.elements.length
}
})
;Rye.define('Manipulation', function(){
var util = Rye.require('Util')
, query = Rye.require('Query')
, _slice = Array.prototype.slice
function getValue(element) {
if (element.multiple) {
return new Rye(element).find('option').filter(function(option) {
return option.selected && !option.disabled
}).pluck('value')
}
return element.value
}
function getAttribute(element, name) {
if (name === 'value' && element.nodeName == 'INPUT') {
return getValue(element)
}
return element.getAttribute(name)
}
function append (element, html) {
if (typeof html === 'string') {
element.insertAdjacentHTML('beforeend', html)
} else {
element.appendChild(html)
}
}
function prepend (element, html) {
var first
if (typeof html === 'string') {
element.insertAdjacentHTML('afterbegin', html)
} else if (first = element.childNodes[0]){
element.insertBefore(html, first)
} else {
element.appendChild(html)
}
}
function after (element, html) {
var next
if (typeof html === 'string') {
element.insertAdjacentHTML('afterend', html)
} else if (next = query.getClosestNode(element, 'nextSibling')) {
element.parentNode.insertBefore(html, next)
} else {
element.parentNode.appendChild(html)
}
}
function before (element, html) {
if (typeof html === 'string') {
element.insertAdjacentHTML('beforebegin', html)
} else {
element.parentNode.insertBefore(html, element)
}
}
function proxyExport(fn, method) {
// This function coerces the input into either a string or an array of elements,
// then passes it on to the appropriate method, iterating if necessary.
this[method] = function (obj) {
if (typeof obj !== 'string'){
if (obj instanceof Rye) {
obj = obj.elements
} else if (util.isNodeList(obj)) {
obj = _slice.call(obj)
}
// Also support arrays [el1, el2, ...]
if (Array.isArray(obj)) {
if (/prepend|before/.test(method)){
obj = _slice.call(obj, 0).reverse()
}
return obj.forEach(this[method].bind(this))
}
}
if (this.length === 1) {
fn(this.elements[0], obj)
} else {
this.each(function(element, i){
var node = i > 0 ? obj.cloneNode(true) : obj
fn(element, node)
})
}
return this
}
}
// Patch methods, add to prototype
util.each({
append : append
, prepend : prepend
, after : after
, before : before
}, proxyExport.bind(this))
this.text = function (text) {
if (text == null) {
return this.elements[0] && this.elements[0].textContent
}
return this.each(function(element){
element.textContent = text
})
}
this.html = function (html) {
if (html == null) {
return this.elements[0] && this.elements[0].innerHTML
}
return this.each(function(element){
element.innerHTML = html
})
}
this.empty = function () {
return this.put('innerHTML', '')
}
this.clone = function () {
return this.map(function(element){
return element.cloneNode(true)
})
}
this.remove = function () {
return this.each(function(element){
if (element.parentNode) {
element.parentNode.removeChild(element)
}
})
}
this.val = function (value) {
if (value == null) {
return this.elements[0] && getValue(this.elements[0])
}
return this.each(function(element){
element.value = value
})
}
this.attr = function (name, value) {
if (typeof name === 'object'){
return this.each(function(element){
util.each(name, function(value, key){
element.setAttribute(key, value)
})
})
}
return typeof value === 'undefined'
? this.elements[0] && getAttribute(this.elements[0], name)
: this.each(function(element){
element.setAttribute(name, value)
})
}
this.prop = function (name, value) {
if (typeof name === 'object'){
return this.each(function(element){
util.each(name, function(value, key){
element[key] = value
})
})
}
return typeof value === 'undefined'
? this.elements[0] && this.elements[0][name]
: this.put(name, value)
}
Rye.create = function (html) {
var temp = document.createElement('div')
, children
temp.innerHTML = html
children = _slice.call(temp.childNodes)
children.forEach(function(node, i){
temp.removeChild(node)
})
return new Rye(children)
}
return {
getValue : getValue
, getAttribute : getAttribute
, append : append
, prepend : prepend
, after : after
, before : before
}
})
;Rye.define('Events', function(){
var util = Rye.require('Util')
, query = Rye.require('Query')
, _slice = Array.prototype.slice
// General-purpose event emitter
// -----------------------------
function EventEmitter () {
this.events = {}
this.context = null
}
// Adds a handler to the events list
EventEmitter.prototype.addListener = function (event, handler) {
var handlers = this.events[event] || (this.events[event] = [])
handlers.push(handler)
return this
}
// Add a handler that can only get called once
EventEmitter.prototype.once = function (event, handler) {
var self = this
function suicide () {
handler.apply(this, arguments)
self.removeListener(event, suicide)
}
return this.addListener(event, suicide)
}
// Removes a handler from the events list
EventEmitter.prototype.removeListener = function (event, handler) {
var self = this
, handlers = this.events[event]
if (event === '*') {
if (!handler) {
this.events = {}
} else {
util.each(this.events, function(handlers, event){
self.removeListener(event, handler)
})
}
} else if (handler && handlers) {
handlers.splice(handlers.indexOf(handler), 1)
if (handlers.length === 0) {
delete this.events[event]
}
} else {
delete this.events[event]
}
return this
}
// Calls all handlers that match the event type
EventEmitter.prototype.emit = function (event) {
var handlers = this.events[event]
, args = _slice.call(arguments, 1)
, context = this.context || this
if (handlers) {
util.each(handlers, function(fn) {
fn.apply(context, args)
})
}
return this
}
EventEmitter.prototype.proxy = function (event) {
return util.applyLeft(this, this.emit, [event])
}
// Utility methods
// -----------------------------
var emitters = {}
function getEmitter (element) {
var id = util.getUid(element)
return emitters[id] || (emitters[id] = new DOMEventEmitter(element))
}
function getType (event) {
var index = event.indexOf(' ')
return index > 0 ? event.substr(0, index) : event
}
function getSelector (event) {
var index = event.indexOf(' ')
return index > 0 ? event.substr(index) : ''
}
function createEvent (type, properties) {
if (typeof type != 'string') {
type = type.type
}
var isMouse = ['click', 'mousedown', 'mouseup', 'mousemove'].indexOf(type) != -1
, event = document.createEvent(isMouse ? 'MouseEvent' : 'Event')
if (properties) {
util.extend(event, properties)
}
event.initEvent(type, true, true)
return event
}
// DOM event emitter
// -----------------------------
/*
Creates one event emitter per element, proxies DOM events to it. This way
we can keep track of the functions so that they can be removed from the
elements by reference when you call .removeListener() by event name.
*/
function DOMEventEmitter (element) {
EventEmitter.call(this)
this.element = element
this.proxied = {}
}
util.inherits(DOMEventEmitter, EventEmitter)
DOMEventEmitter.prototype._proxy = function (event) {
return function (DOMEvent) {
var selector = getSelector(event)
, context = this.element
// delegate behavior
if (selector) {
context = DOMEvent.target
while (context && !query.matches(context, selector)) {
context = context !== this.element && context.parentNode
}
if (!context || context == this.element) {
return
}
}
this.context = context
this.emit(event, DOMEvent, this.element)
}.bind(this)
}
DOMEventEmitter.prototype.proxy = function (event) {
return this.proxied[event] || (this.proxied[event] = this._proxy(event))
}
DOMEventEmitter.prototype.addListener = function (event, handler) {
EventEmitter.prototype.addListener.call(this, event, handler)
if (!this.proxied[event]) {
this.element.addEventListener(getType(event), this.proxy(event), false)
}
return this
}
DOMEventEmitter.prototype.removeListener = function (event, handler) {
if (event.indexOf('*') >= 0) {
var self = this
, re = new RegExp('^' + event.replace('*', '\\b'))
// * : remove all events
// type * : remove delegate events
// type* : remove delegate and undelegate
util.each(this.events, function(handlers, event){
if (re.test(event)) {
self.removeListener(event, handler)
}
})
} else {
var proxy = this.proxied[event]
EventEmitter.prototype.removeListener.call(this, event, handler)
if (!this.events[event] && proxy) {
this.element.removeEventListener(getType(event), proxy, false)
delete this.proxied[event]
}
}
return this
}
function acceptMultipleEvents (method) {
var _method = DOMEventEmitter.prototype[method]
DOMEventEmitter.prototype[method] = function (event, handler) {
var self = this
if (typeof event !== 'string') {
util.each(event, function(handler, event){
_method.call(self, event, handler)
})
} else {
_method.call(self, event, handler)
}
return self
}
}
;['addListener', 'once', 'removeListener'].forEach(acceptMultipleEvents)
DOMEventEmitter.prototype.destroy = function () {
return this.removeListener('*')
}
DOMEventEmitter.prototype.trigger = function (event, data) {
if (!(event instanceof window.Event)) {
event = createEvent(event)
}
event.data = data
this.element.dispatchEvent(event)
return this
}
// Exported methods
// -----------------------------
var exports = {}
function emitterProxy (method, element, event, handler) {
getEmitter(element)[method](event, handler)
}
;['addListener', 'removeListener', 'once', 'trigger'].forEach(function(method){
// Create a function proxy for the method
var fn = util.curry(emitterProxy, method)
// Exports module and rye methods
exports[method] = fn
this[method] = this.iterate(fn)
}.bind(this))
// Aliases
// -----------------------------
;[EventEmitter.prototype, DOMEventEmitter.prototype, this].forEach(function(obj){
obj.on = obj.addListener
})
// Global event bus / pub-sub
// -----------------------------
var EE = new EventEmitter
Rye.subscribe = EE.addListener.bind(EE)
Rye.unsubscribe = EE.removeListener.bind(EE)
Rye.publish = EE.emit.bind(EE)
return {
EventEmitter : EventEmitter
, DOMEventEmitter : DOMEventEmitter
, getEmitter : getEmitter
, createEvent : createEvent
, addListener : exports.addListener
, once : exports.once
, removeListener : exports.removeListener
, trigger : exports.trigger
}
})
;Rye.define('Style', function(){
var util = Rye.require('Util')
, data = Rye.require('Data')
, _cssNumber = 'fill-opacity font-weight line-height opacity orphans widows z-index zoom'.split(' ')
function getCSS (element, property) {
return element.style.getPropertyValue(property)
|| window.getComputedStyle(element, null).getPropertyValue(property)
}
function setCSS (element, property, value) {
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if (typeof value == 'number' && _cssNumber.indexOf(property) === -1) {
value += 'px'
}
var action = (value === null || value === '') ? 'remove' : 'set'
element.style[action + 'Property'](property, '' + value)
return element
}
function hasClass (element, name) {
name = name.trim()
return element.classList ?
element.classList.contains(name)
: (' ' + element.className + ' ').indexOf(' ' + name + ' ') !== -1
}
function addClass (element, names) {
if (element.classList) {
names.replace(/\S+/g, function(name){ element.classList.add(name) })
} else {
var classes = ' ' + element.className + ' ', name
names = names.trim().split(/\s+/)
while (name = names.shift()) {
if (classes.indexOf(' ' + name + ' ') === -1) {
classes += name + ' '
}
}
element.className = classes.trim()
}
return element
}
function removeClass (element, names) {
if (names === '*') {
element.className = ''
} else {
if (names instanceof RegExp) {
names = [names]
} else if (element.classList && names.indexOf('*') === -1) {
names.replace(/\S+/g, function(name){ element.classList.remove(name) })
return
} else {
names = names.trim().split(/\s+/)
}
var classes = ' ' + element.className + ' ', name
while (name = names.shift()) {
if (name.indexOf && name.indexOf('*') !== -1) {
name = new RegExp('\\s*\\b' + name.replace('*', '\\S*') + '\\b\\s*', 'g')
}
if (name instanceof RegExp) {
classes = classes.replace(name, ' ')
} else {
while (classes.indexOf(' ' + name + ' ') !== -1) {
classes = classes.replace(' ' + name + ' ', ' ')
}
}
}
element.className = classes.trim()
}
return element
}
this.show = this.iterate(function(element){
setCSS(element, 'display', data.get(element, '_display') || 'block')
})
this.hide = this.iterate(function(element){
var _display = getCSS(element, 'display')
if (_display !== 'none') {
data.set(element, '_display', _display)
}
setCSS(element, 'display', 'none')
})
this.css = function (property, value) {
if (value == null) {
if (typeof property == 'string') {
return this.elements[0] && getCSS(this.elements[0], property)
}
return this.each(function(element){
util.each(property, function(value, key){
setCSS(element, key, value)
})
})
}
return this.each(function(element){
setCSS(element, property, value)
})
}
this.hasClass = function (name) {
var result = false
this.each(function(element){
result = result || hasClass(element, name)
})
return !!result
}
this.addClass = this.iterate(addClass)
this.removeClass = this.iterate(removeClass)
this.toggleClass = this.iterate(function(element, name, when){
if (when == null) {
when = !hasClass(element, name)
}
(when ? addClass : removeClass)(element, name)
})
return {
getCSS : getCSS
, setCSS : setCSS
, hasClass : hasClass
, addClass : addClass
, removeClass : removeClass
}
})
;Rye.define('TouchEvents', function(){
var util = Rye.require('Util')
, events = Rye.require('Events')
, touch = {}
// checks if it needed
function parentIfText (node) {
return 'tagName' in node ? node : node.parentNode
}
function Gesture(props) {
util.extend(this, props)
Gesture.all.push(this)
}
Gesture.all = []
Gesture.cancelAll = function () {
Gesture.all.forEach(function(instance){
instance.cancel()
})
touch = {}
}
Gesture.prototype.schedule = function () {
this.timeout = setTimeout(this._trigger.bind(this), this.delay)
}
Gesture.prototype._trigger = function () {
this.timeout = null
this.trigger()
}
Gesture.prototype.cancel = function () {
if (this.timeout) {
clearTimeout(this.timeout)
}
this.timeout = null
}
if (events && ('ontouchstart' in window || window.mocha)) {
var tap = new Gesture({
delay: 0
, trigger: function () {
// cancelTouch cancels processing of single vs double taps for faster 'tap' response
var event = events.createEvent('tap')
event.cancelTouch = Gesture.cancelAll
events.trigger(touch.element, event)
// trigger double tap immediately
if (touch.isDoubleTap) {
events.trigger(touch.element, 'doubletap')
touch = {}
// trigger single tap after (x)ms of inactivity
} else {
singleTap.schedule()
}
}
})
, singleTap = new Gesture({
delay: 250
, trigger: function () {
events.trigger(touch.element, 'singletap')
touch = {}
}
})
, longTap = new Gesture({
delay: 750
, trigger: function () {
if (touch.last) {
events.trigger(touch.element, 'longtap')
touch = {}
}
}
})
, swipe = new Gesture({
delay: 0
, trigger: function () {
events.trigger(touch.element, 'swipe')
events.trigger(touch.element, 'swipe' + this.direction())
touch = {}
}
, direction: function () {
if (Math.abs(touch.x1 - touch.x2) >= Math.abs(touch.y1 - touch.y2)) {
return touch.x1 - touch.x2 > 0 ? 'left' : 'right'
}
return touch.y1 - touch.y2 > 0 ? 'up' : 'down'
}
})
events.addListener(document.body, 'touchstart', function (event) {
var now = Date.now()
singleTap.cancel()
touch.element = parentIfText(event.touches[0].target)
touch.x1 = event.touches[0].pageX
touch.y1 = event.touches[0].pageY
if (touch.last && (now - touch.last) <= 250) {
touch.isDoubleTap = true
}
touch.last = now
longTap.schedule()
})
events.addListener(document.body, 'touchmove', function (event) {
longTap.cancel()
touch.x2 = event.touches[0].pageX
touch.y2 = event.touches[0].pageY
})
events.addListener(document.body, 'touchend', function () {
longTap.cancel()
// swipe
if (Math.abs(touch.x1 - touch.x2) > 30 || Math.abs(touch.y1 - touch.y2) > 30) {
swipe.schedule()
// normal tap
} else if ('last' in touch) {
tap.schedule()
}
})
events.addListener(document.body, 'touchcancel', Gesture.cancelAll)
events.addListener(window, 'scroll', Gesture.cancelAll)
}
})
;Rye.define('Request', function(){
var util = Rye.require('Util')
, manipulation = Rye.require('Manipulation')
, noop = function(){}
, escape = encodeURIComponent
, accepts = {
types : ['arraybuffer', 'blob', 'document', 'json', 'text']
, json : 'application/json'
, xml : 'application/xml, text/xml'
, html : 'text/html, application/xhtml+xml'
, text : 'text/plain'
}
, defaults = {
method : 'GET'
, url : window.location.toString()
, async : true
, accepts : accepts
, callback : noop
, timeout : 0
// , headers : {}
// , contentType : null
// , data : null
// , responseType : null
// , headers : null
}
function serialize (obj) {
var params = []
;(function fn (obj, scope) {
util.each(obj, function(value, key){
value = obj[key]
if (scope) {
key = scope + '[' + (Array.isArray(obj) ? '' : key) + ']'
}
if (util.is(['array', 'object'], value)) {
fn(value, key)
} else {
params.push(escape(key) + '=' + escape(value))
}
})
})(obj)
return params.join('&').replace(/%20/g, '+')
}
function appendQuery (url, query) {
return (url + '&' + query).replace(/[&?]+/, '?')
}
function parseData (options) {
if (options.data && (typeof options.data !== 'string')) {
options.data = serialize(options.data)
}
if (options.data && options.method === 'GET') {
options.url = appendQuery(options.url, options.data)
}
}
function parseMime (mime) {
return mime && (mime.split('/')[1] || mime)
}
function parseJSON (xhr) {
var data = xhr.response
// error of responseType: json
if (data === null) {
return new Error('Parser Error')
}
if (typeof data !== 'object') {
try {
data = JSON.parse(xhr.responseText)
} catch (err) {
return err
}
}
return data
}
function parseXML (xhr) {
var data = xhr.responseXML
// parse xml to IE 9
if (data.xml && window.DOMParser) {
try {
var parser = new window.DOMParser()
data = parser.parseFromString(data.xml, 'text/xml')
} catch (err) {
return err
}
}
return data
}
function request (options, callback) {
if (typeof options === 'string') {
options = { url: options }
}
if (!callback) {
callback = options.callback || noop
}
var settings = util.extend({}, defaults, options)
, xhr = new window.XMLHttpRequest()
, mime = settings.accepts[settings.responseType]
, abortTimeout = null
, headers = {}
settings.method = settings.method.toUpperCase()
parseData(settings)
// sets request's accept and content type
if (mime) {
headers['Accept'] = mime
if (xhr.overrideMimeType) {
xhr.overrideMimeType(mime.split(',')[0])
}
}
if (settings.contentType || ['POST', 'PUT'].indexOf(settings.method) >= 0) {
headers['Content-Type'] = settings.contentType || 'application/x-www-form-urlencoded'
}
util.extend(headers, settings.headers || {})
xhr.onreadystatechange = function(){
var err, data
if (xhr.readyState != 4 || !xhr.status) {
return
}
xhr.onreadystatechange = noop
clearTimeout(abortTimeout)
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
xhr.type = settings.responseType || xhr.responseType || parseMime(xhr.getResponseHeader('content-type'))
switch (xhr.type) {
case 'json':
data = parseJSON(xhr)
break
case 'xml':
data = parseXML(xhr)
break
default:
data = xhr.responseText
}
if (data instanceof Error) {
err = data, data = undefined
}
} else {
err = new Error('Request failed')
}
callback.call(xhr, err, data, xhr)
}
xhr.ontimeout = function(){
callback.call(xhr, new Error('Timeout'), null, xhr)
}
xhr.open(settings.method, settings.url, settings.async)
// implements fallback to request's abort by timeout
if (!('timeout' in xhr) && settings.timeout > 0) {
abortTimeout = setTimeout(function(){
xhr.onreadystatechange = noop
xhr.abort()
xhr.ontimeout()
}, settings.timeout)
}
// exports settings to xhr and sets headers
util.each(settings, function(value, key) {
if (key !== 'responseType' || accepts.types.indexOf(value) >= 0) {
try { xhr[key] = value } catch (e) {}
}
})
util.each(headers, function(value, name) {
xhr.setRequestHeader(name, value)
})
xhr.send(settings.data)
return xhr
}
function requestProxy (method, options, callback) {
if (typeof options === 'string') {
options = { url: options }
}
options.method = method
return request(options, callback)
}
var hideTypes = 'fieldset submit reset button image radio checkbox'.split(' ')
this.serialize = function () {
var form = this.get(0)
, fields = {}
new Rye(form && form.elements).forEach(function(field){
if (!field.disabled && (
field.checked
|| (field.type && hideTypes.indexOf(field.type) < 0)
)
) {
fields[field.name] = manipulation.getValue(field)
}
})
return serialize(fields)
}
// Exported methods
// ----------------
Rye.request = request
Rye.get = util.curry(requestProxy, 'GET')
Rye.post = util.curry(requestProxy, 'POST')
// prevents to attach properties on request
var exports = request.bind({})
util.extend(exports, {
serialize : serialize
, appendQuery : appendQuery
, defaults : defaults
, get : util.curry(requestProxy, 'GET')
, post : util.curry(requestProxy, 'POST')
// https://github.com/mlbli/craft/blob/master/src/ajax.js#L77
})
return exports
})
| mneudert/caribou | public/vendor/js/rye-0.1.0.js | JavaScript | mit | 44,602 |
"use strict"
// Module to handle simple matching
var Game = require("./Game.js")
var config = require("./config.js")
var MSG_OUT_SIMPLE_MATCH_PROGRESS = 1
// Storage to all waiting players
var _rooms = (function () {
var r = [], n
for (n=config.maxPlayers; n>=config.minPlayers; n--)
r[n] = []
return r
})()
// Handle a new player in the line
module.exports.start = function (player, data) {
var i, num
// Validate the input
if (!Array.isArray(data.wishes)) {
log("Invalid start simple match data, closing connection")
player.close()
return
}
for (i=0; i<data.wishes.length; i++) {
num = data.wishes[i]
if (typeof num != "number" || Math.round(num) != num || num < config.minPlayers || num > config.maxPlayers) {
log("Invalid start simple match data, closing connection")
player.close()
return
}
}
// Add to the rooms and check if a match can be done
data.wishes.sort(function (a, b) {
return b-a
})
log("New player waiting for "+data.wishes.join(" or ")+" players")
for (i=0; i<data.wishes.length; i++) {
num = data.wishes[i]
_rooms[num].push(player)
if (_rooms[num].length == num) {
// Create the match
doMatch(num)
break
}
}
// Inform everybody about the status
informProgress()
}
// Remove a given player from the matching system
module.exports.remove = function (player) {
var n, pos
// Remove from all rooms
log("Player leaving simple match")
for (n=config.maxPlayers; n>=config.minPlayers; n--) {
pos = _rooms[n].indexOf(player)
if (pos != -1)
_rooms[n].splice(pos, 1)
}
// Inform everybody about the status
informProgress()
}
// Create a match with the given number of players
function doMatch(num) {
var players, n, pos, j, before
players = _rooms[num]
log("Simple match done with "+num+" players")
// Remove these players from all other rooms
for (n=config.maxPlayers; n>=config.minPlayers; n--) {
if (n == num)
continue
before = _rooms[n]
_rooms[n] = []
for (j=0; j<before.length; j++)
if (players.indexOf(before[j]) == -1)
_rooms[n].push(before[j])
}
new Game(players)
_rooms[num] = []
}
// Send to every body in the waiting room the current status of all rooms
function informProgress() {
var data, n, idsAlerted, i, player
// Collect all data
data = []
for (n=config.maxPlayers; n>=config.minPlayers; n--)
data.push({wanted: n, waiting: _rooms[n].length})
// Broadcast
idsAlerted = {}
for (n=config.maxPlayers; n>=config.minPlayers; n--)
for (i=0; i<_rooms[n].length; i++) {
player = _rooms[n][i]
if (!(player.id in idsAlerted)) {
player.sendMessage(MSG_OUT_SIMPLE_MATCH_PROGRESS, data)
idsAlerted[player.id] = true
}
}
}
function log(str) {
if (config.logConnections)
console.log("> "+str)
}
| codeca/splendens | server/simpleMatch.js | JavaScript | mit | 2,765 |
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
pages: __dirname +'/app/src/router.jsx',
vendors:['react','react-dom','react-router'] //抽取公共框架
},
output: {
path: __dirname + '/app/dist',
publicPath:'dist', //事实上,这个配置直接影响了图片的输出路径
filename: 'js/bundle.js'
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract({fallback: 'style-loader',use: 'css-loader'}) }, //坑:不能用叹号链接,必须写成这种格式
{ test: /\.less$/, loader: ExtractTextPlugin.extract({use: 'css-loader!less-loader'}) },
{ test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192&name=/img/[name].[ext]' },
{ test: /\.(woff|woff2|eot|ttf|svg)(\?.*$|$)/, loader: 'url-loader' }
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({name: 'vendors', filename: 'js/vendors.js'}),
new ExtractTextPlugin("css/bundle.css"),
new webpack.ProvidePlugin({ $: "jquery" }),
// 压缩配置
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
// 配置环境变量到Production,防止控制台警告
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
})
]
};
| liubixu/blog-react | webpack.production.config.js | JavaScript | mit | 1,693 |
module.exports = {
book: {
assets: "./book",
js: [
"code-tomorrow-scheme.js",
"plugin.js"
],
css: [
"code-tomorrow-scheme.css"
]
},
blocks: {
code: {
process: function(blk) {
}
}
}
};
| rubengarciam/rubengarciam.github.io | notes/md/node_modules/gitbook-plugin-code_tomorrow_scheme/index.js | JavaScript | mit | 215 |
var path = require('path');
var fs = require('fs');
var Checker = require('../../lib/checker');
var assert = require('assert');
describe('options/file-extensions', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
});
describe('default config', function() {
beforeEach(function() {
checker.configure({
disallowKeywords: ['with']
});
});
it('should report errors for matching extensions (case insensitive) in directory with default config',
function() {
return checker.checkDirectory('./test/data/options/file-extensions').then(function(errors) {
assert(errors.length === 2);
});
}
);
});
describe('custom config', function() {
it('should report errors for matching extensions with custom config', function() {
checker.configure({
fileExtensions: ['.jsx'],
disallowKeywords: ['with']
});
return checker.checkDirectory('./test/data/options/file-extensions').then(function(errors) {
assert(errors.length === 1);
});
});
it('should report errors for matching extensions (case insensitive) with custom config', function() {
checker.configure({
fileExtensions: ['.JS'],
disallowKeywords: ['with']
});
return checker.checkDirectory('./test/data/options/file-extensions').then(function(errors) {
assert(errors.length === 2);
});
});
it('should report errors for matching extensions (case insensitive) with string value', function() {
checker.configure({
fileExtensions: '.JS',
disallowKeywords: ['with']
});
assert(checker.checkFile('./test/data/options/file-extensions/file-extensions-2.jS') !== null);
return checker.checkDirectory('./test/data/options/file-extensions').then(function(errors) {
assert(errors.length === 2);
});
});
it('should report errors for matching extensions with custom config with multiple extensions', function() {
checker.configure({
fileExtensions: ['.js', '.jsx'],
disallowKeywords: ['with']
});
assert(checker.checkFile('./test/data/options/file-extensions/file-extensions.js') !== null);
assert(checker.checkFile('./test/data/options/file-extensions/file-extensions.jsx') !== null);
return checker.checkDirectory('./test/data/options/file-extensions').then(function(errors) {
assert(errors.length === 3);
});
});
it('should report errors for matching extensions with Array *', function() {
var testPath = './test/data/options/file-extensions';
checker.configure({
fileExtensions: ['*'],
disallowKeywords: ['with']
});
return checker.checkDirectory(testPath).then(function(errors) {
assert(errors.length === fs.readdirSync(testPath).length);
});
});
it('should report errors for matching extensions with string *', function() {
var testPath = './test/data/options/file-extensions';
checker.configure({
fileExtensions: '*',
disallowKeywords: ['with']
});
return checker.checkDirectory(testPath).then(function(errors) {
assert(errors.length === fs.readdirSync(testPath).length);
});
});
it('should report errors for file whose fullname is the same as matching extension', function() {
checker.configure({
fileExtensions: 'file-extensions',
disallowKeywords: ['with']
});
return checker.checkDirectory('./test/data/options/file-extensions').then(function(errors) {
assert(errors.length === 1);
});
});
});
it('should be present in config after initialization', function() {
checker.configure({
fileExtensions: 'test'
});
var config = checker.getProcessedConfig();
assert(config.fileExtensions !== undefined);
assert(Object.getOwnPropertyDescriptor(config, 'fileExtensions').enumerable === false);
});
});
| addyosmani/node-jscs | test/options/file-extensions.js | JavaScript | mit | 4,599 |
YUI.add('treeview-tests', function(Y) {
var A = Y.Assert,
TV = Y.FWTreeView,
SELECTED = 'selected',
EXPANDED = 'expanded',
LABEL = 'label',
ID = 'id',
buildTree = function (levels, width, expanded) {
var build = function (prefix, depth) {
var i, branch = [];
for (i = 0; i < width; i += 1) {
branch[i] = {label: prefix + '-' + i};
if (expanded !== undefined) {
branch[i].expanded = expanded;
}
if (depth < levels -1) {
branch[i].children = build(prefix + '-' + i, depth + 1);
}
}
return branch;
};
return build('label', 0);
},
treeDef = buildTree(3,3,false),
suite = new Y.Test.Suite("FWTreeView Test Suite");
suite.add(new Y.Test.Case({
name: "FWTreeView",
'Test dynamic Loading': function () {
var node, other, tv = new TV({
tree: [
'label-0',
'label-1',
'label-2'
],
dynamicLoader: function (node, callback) {
var i, branch = [],
label = node.get(LABEL);
for (i = 0; i < 3; i += 1) {
branch[i] = label + '-' + i;
}
callback(branch);
}
});
tv.render();
tv.getNodeBy(LABEL,'label-1').expand().release();
tv.getNodeBy(LABEL,'label-1-1').expand().release();
tv.getNodeBy(LABEL,'label-1-1-0').expand().release();
tv.getNodeBy(LABEL,'label-2').expand().release();
node = tv.getNodeBy(LABEL,'label-1-1-0-1');
A.areEqual(3, node.get('depth'), 'node 1-1-0-1 should be at depth 3');
A.areEqual('label-1-1-0-1', node.get(LABEL), 'node should be labeled label 1-1-0-1');
other = node.getNextSibling();
A.areEqual(3, other.get('depth'), 'node 1-1-0-2 should be at depth 3');
A.areEqual('label-1-1-0-2', other.get(LABEL), 'node should be labeled label 1-1-0-2');
A.isNull(other.getNextSibling(),' there should be no next to 1-1-0-2');
other.release();
other = node.getPreviousSibling();
A.areEqual(3, other.get('depth'), 'node 1-1-0-0 should be at depth 3');
A.areEqual('label-1-1-0-0', other.get(LABEL), 'node should be labeled label 1-1-0-0');
A.isNull(other.getPreviousSibling(),' there should be no next to 1-1-0-0');
other.release();
other = node.getParent();
A.areEqual(2, other.get('depth'), 'node 1-1-0 should be at depth 2');
A.areEqual('label-1-1-0', other.get(LABEL), 'node should be labeled label 1-1-0');
other.release();
node.release();
tv.destroy();
},
'Test selection': function () {
var tv,
check = function (which) {
tv.forSomeNodes(function (node) {
A.areEqual(parseInt(node.get(LABEL),10), node.get(SELECTED), which + ': ' + node.get(ID));
});
},
build = function(tree) {
tv = (new TV({tree:tree})).render('#container');
},
buildAndCheck = function(which, tree) {
build(tree);
check(which);
tv.destroy();
};
buildAndCheck('silly test not selected', [
{
id:'a',
label:0
}
]);
buildAndCheck('silly test selected',[
{
id:'a',
label: 2,
selected:true
}
]);
build([
{
id:'a',
label:0,
children: [
{
id:'b',
label: 0
}
]
}
]);
check('initially all off');
tv.getNodeBy(ID,'b').set(SELECTED,true).set(LABEL, 2).release();
tv.getNodeBy(ID,'a').set(LABEL, 2).release();
check('selection should have moved up');
tv.destroy();
},
'test a node type with no label': function () {
var TVNoLabel = Y.Base.create(
'no-label-node',
Y.FWTreeNode,
[ ],
{ },
{
INNER_TEMPLATE: '<div tabIndex="{tabIndex}" class="{CNAME_CONTENT}"><div class="{CNAME_TOGGLE}"></div>' +
'<div class="{CNAME_BAD_LABEL}" role="link">{label}</div></div>'
}
), tv = new TV({
tree: [
{
label: 'abc',
type: TVNoLabel
},{
label: 'def',
type: TVNoLabel
}
]
});
tv.render('#container');
var node = tv.getNodeBy(LABEL,'abc');
node.set(LABEL,'123');
A.areEqual('123', node.get(LABEL));
node.release();
tv.destroy();
},
'Test some clicking': function () {
var tv = new TV({tree: treeDef}),
node = tv.getNodeBy(LABEL, 'label-1-1'),
el;
tv.render('#container');
tv.set('focusedNode', node);
A.isFalse(node.get(EXPANDED), 'node should not be expanded yet');
el = Y.one('#' + node.get(ID) + ' .' + Y.FWTreeNode.CNAMES.CNAME_TOGGLE);
el.simulate('click');
A.isTrue(node.get(EXPANDED), 'node should be expanded');
el.simulate('click');
A.isFalse(node.get(EXPANDED), 'node should not be expanded');
A.areEqual(0, node.get(SELECTED), 'node should not be selected');
el = Y.one('#' + node.get(ID) + ' .' + Y.FWTreeNode.CNAMES.CNAME_SELECTION);
el.simulate('click');
A.areEqual(2, node.get(SELECTED), 'node should now be selected');
el = Y.one('#' + node.get(ID) + ' .' + Y.FWTreeNode.CNAMES.CNAME_LABEL);
el.simulate('click');
A.areEqual(2, node.get(SELECTED), 'clicking on the label should not change anything');
A.isFalse(node.get(EXPANDED), 'clicking on the label should not change anything');
tv.set('toggleOnLabelClick', true);
el.simulate('click');
A.isTrue(node.get(EXPANDED), 'with toggleOnLabelClick set, it should expand');
el = Y.one('#' + node.get(ID) + ' .' + Y.FWTreeNode.CNAMES.CNAME_ICON);
el.simulate('click');
A.isFalse(node.get(EXPANDED), 'clicking on the label should not change anything');
tv.set('toggleOnLabelClick', true);
el.simulate('click');
A.isTrue(node.get(EXPANDED), 'with toggleOnLabelClick set, it should expand');
el = Y.one('#' + node.get(ID) + ' .' + Y.FWTreeNode.CNAMES.CNAME_CONTENT);
el.simulate('click');
A.isTrue(node.get(EXPANDED), 'with toggleOnLabelClick set, it should expand');
A.areEqual(2, node.get(SELECTED), 'clicking on the label should not change anything');
node.release();
tv.destroy();
},
'Test focused node gets expanded': function () {
var tv = new TV({tree: treeDef});
tv.render('#container');
tv.forSomeNodes(function (node) {
A.isFalse(node.hasChildren() && node.get(EXPANDED), 'All nodes should be collapsed:' + node.get(LABEL));
});
var focusedTest = function (label) {
var focusedNode = tv.getNodeBy(LABEL, label);
tv.set('focusedNode', focusedNode);
var node , ancestor = focusedNode , ancestry = [];
while (ancestor) {
node = ancestor;
ancestor = ancestor.getParent();
node.release();
if (!ancestor) {
break;
}
ancestry.push(ancestor.get(ID));
}
tv.forSomeNodes(function (node) {
if (ancestry.indexOf(node.get(ID)) !== -1) {
A.isTrue(node.get(EXPANDED), 'Ancestors of ' + label + ' should be expanded: ' + node.get(LABEL));
} else {
A.isFalse(node.hasChildren() && node.get(EXPANDED), 'Only the ancestors of ' + label + ' should be expanded:' + node.get(LABEL));
}
});
focusedNode.release();
};
focusedTest('label-1-1-1');
tv.collapseAll();
focusedTest('label-1-1');
tv.destroy();
},
'Requesting a held node should return the same reference': function () {
var tv = new TV({tree:treeDef}),
node = tv.getNodeBy(LABEL, 'label-1'),
other = tv.getNodeBy(LABEL, 'label-1');
A.areSame(node, other, 'Node references should be the same');
node.release();
other.release();
tv.destroy();
},
'test toggle Selection' : function () {
var tv = new TV({tree: treeDef});
tv.render('#container');
var node = tv.getNodeBy(LABEL, 'label-1');
A.areEqual(0,node.get(SELECTED), 'node should start unselected');
node.toggleSelection();
A.areEqual(2,node.get(SELECTED), 'node should now be selected');
node.toggleSelection();
A.areEqual(0,node.get(SELECTED), 'node should now be unselected');
node.toggleSelection();
A.areEqual(2,node.get(SELECTED), 'node should now be selected again');
A.isTrue(node.get('propagateUp'),'propagateUp should be enabled');
A.isTrue(node.get('propagateDown'),'propagateDown should be enabled');
node.set('selectionEnabled', false);
A.isNull(node.get(SELECTED), 'When selection is not enabled it should return null');
A.isFalse(node.get('propagateUp'),'propagateUp should be disabled (disabled nodes do not propagete)');
A.isFalse(node.get('propagateDown'),'propagateDown should be disabled (disabled nodes do not propagete)');
node.toggleSelection();
A.isNull(node.get(SELECTED), 'even when toggled');
A.areEqual(0,node._iNode[SELECTED], 'Internally it should really change');
var el = Y.one('#' + node.get(ID) + ' .' + Y.FWTreeNode.CNAMES.CNAME_SELECTION);
el.simulate('click');
A.isNull(node.get(SELECTED), 'even when toggled');
node.set('selectionEnabled', true);
A.areEqual(2,node.get(SELECTED), 'node should be selected again as before');
node.toggleSelection();
A.areEqual(0,node.get(SELECTED), 'selection should toggle as before');
tv.destroy();
},
'testing initial values': function () {
var oneTest = function (which) {
var TVNoSelection = Y.Base.create(
'no-selection-node',
Y.FWTreeNode,
[ ],
{ },
{
ATTRS: {
selectionEnabled: {
value: which
},
propagateUp: {
value: which
},
propagateDown: {
value: which
},
expanded: {
value: which
}
}
}
),
tv = new TV({
tree: buildTree(3,3),
defaultType: TVNoSelection
});
tv.render('#container');
tv.forSomeNodes(function (node) {
A.areEqual(which,node.get('selectionEnabled'),which + ' selectionEnabled failed: ' + node.get(LABEL));
A.areEqual(which,node.get('propagateUp'),which + ' propagateUp failed: ' + node.get(LABEL));
A.areEqual(which,node.get('propagateDown'),which + ' propagateDown failed: ' + node.get(LABEL));
A.areEqual(which,node.get(EXPANDED),which + ' expanded failed: ' + node.get(LABEL));
});
tv.destroy();
};
oneTest(true);
oneTest(false);
},
'Moving around with the keys': function () {
var tv = new TV({tree: treeDef});
tv.render('#container');
var cbx = tv.get('contentBox'),
enterPressed = false,
press = function (key) {
cbx.simulate('keydown', {keyCode: key});
},
is = function (label, step) {
var node = tv.get('focusedNode');
A.areEqual('label-' + label, node.get('label'), step + ' Should have moved to: ' + label);
node.release();
},
test = function (key, label, step) {
press(key);
is(label, step);
},
expanded = function (state, step) {
var node = tv.get('focusedNode');
A.areEqual(state, node.get(EXPANDED), 'Should be expanded?: ' + step);
node.release();
},
selected = function (state, step) {
var node = tv.get('focusedNode');
A.areEqual(state, node.get('selected'), 'Should be selected?: ' + step);
node.release();
},
node = tv.getNodeBy(LABEL, 'label-1');
tv.set('focusedNode', node);
node.release();
test(38, '0',1); // up
test(38, '0',2); // up (shouldn't move)
test(40, '1',3); // down
test(40, '2',4); // down
test(40, '2',5); // down (shouldn't move)
test(36, '0',6); // home
expanded(false,6);
test(39, '0',7); // right, first press should expand
expanded(true,7);
test(39, '0-0',8); // right, second press should move
expanded(false,8);
test(39, '0-0',9);
expanded(true,9);
test(39, '0-0-0',10); // right
test(40, '0-0-1',11); // down
test(40, '0-0-2',12); // down
test(40, '0-1',13); // down
test(40, '0-2',14); // down
test(40, '1',15); // down
test(40, '2',16); // down
test(106, '2',17); // * (expand all);
test(39, '2-0',18);
expanded(true,18);
test(39, '2-0-0',19);
test(39, '2-0-0',19); // right: shouldn't have moved
test(40, '2-0-1',20);
test(37, '2-0',21); // left
expanded(true,21);
test(37, '2-0',22); // left
expanded(false,22);
test(37, '2',23); // left
expanded(true,23);
test(37, '2',24); // left
expanded(false,24);
test(37, '2',24.5); // left (shouldn't have moved)'
test(36, '0',25); // home
test(35, '2',26); //end
test(38, '1-2-2',27); //up
test(37, '1-2',28); // left
selected(false,28);
test(32, '1-2',29); // space bar
selected(2,29);
test(39, '1-2-0',30); // right
selected(2,30);
test(38, '1-2',31); //up
test(37, '1-2',32); // left
test(37, '1',33); // left
selected(1,33);
test(38,'0-2-2',34);
selected(0,35);
tv.after('enterkey', function (ev) {
A.areEqual('label-0-2-2', ev.node.get(LABEL), 'Label on enter');
enterPressed = true;
});
A.isFalse(enterPressed, 'before enter key');
test(13,'0-2-2',34) //enter
A.isTrue(enterPressed, 'after enter key');
test(65, '0-2-2',35); // nothing special should happen with any other key
tv.destroy();
},
'doing things in an empty tree': function () {
var tv = new TV({tree: []}),
cbx = tv.get('contentBox'),
press = function (key) {
cbx.simulate('keydown', {keyCode: key});
};
tv.render('#container');
press(13); // enter
press(32); // spacebar
press(35); //end
press(36); // home
press(37); // left
press(38); // up
press(39); //right
press(40); // down
tv.expandAll();
tv.collapseAll();
tv.forSomeNodes(function(node) {
A.fail('shouldn\'t be here: ' + node.get('label'));
});
tv.destroy();
}
}));
Y.Test.Runner.add(suite);
},'', { requires: ['gallery-fwt-treeview', 'test', 'base-build', 'node-event-simulate' ] });
| inikoo/fact | libs/yui/yui3-gallery/src/gallery-fwt-treeview/tests/unit/js/treeview-tests.js | JavaScript | mit | 18,044 |
var Class = require('../../utils/Class');
var GetColor = require('./GetColor');
var GetColor32 = require('./GetColor32');
var Color = new Class({
initialize:
function Color (red, green, blue, alpha)
{
if (red === undefined) { red = 0; }
if (green === undefined) { green = 0; }
if (blue === undefined) { blue = 0; }
if (alpha === undefined) { alpha = 255; }
// All private
this.r = 0;
this.g = 0;
this.b = 0;
this.a = 255;
this.gl = [ 0.0, 0.0, 0.0, 1.0 ];
this._color = 0;
this._color32 = 0;
this._rgba = '';
this.setTo(red, green, blue, alpha);
},
transparent: function ()
{
this.red = 0;
this.green = 0;
this.blue = 0;
this.alpha = 0;
return this.update();
},
// Values are in the range 0 to 255
setTo: function (red, green, blue, alpha)
{
if (alpha === undefined) { alpha = 255; }
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
return this.update();
},
// Values are in the range 0 to 1
setGLTo: function (red, green, blue, alpha)
{
if (alpha === undefined) { alpha = 1; }
this.redGL = red;
this.greenGL = green;
this.blueGL = blue;
this.alphaGL = alpha;
return this.update();
},
setFromRGB: function (color)
{
this.red = color.r;
this.green = color.g;
this.blue = color.b;
if (color.hasOwnProperty('a'))
{
this.alpha = color.a;
}
return this.update();
},
update: function ()
{
this._color = GetColor(this.r, this.g, this.b);
this._color32 = GetColor32(this.r, this.g, this.b, this.a);
this._rgba = 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + (this.a / 255) + ')';
return this;
},
// Same as setRGB but performs safety checks on all the values given
clone: function ()
{
return new Color(this.r, this.g, this.b, this.a);
},
color: {
get: function ()
{
return this._color;
}
},
color32: {
get: function ()
{
return this._color32;
}
},
rgba: {
get: function ()
{
return this._rgba;
}
},
// Gets and sets the red value, normalized to the 0 to 1 range
redGL: {
get: function ()
{
return this.gl[0];
},
set: function (value)
{
this.gl[0] = Math.min(Math.abs(value), 1);
this.r = Math.floor(this.gl[0] * 255);
this.update();
}
},
greenGL: {
get: function ()
{
return this.gl[1];
},
set: function (value)
{
this.gl[1] = Math.min(Math.abs(value), 1);
this.g = Math.floor(this.gl[1] * 255);
this.update();
}
},
blueGL: {
get: function ()
{
return this.gl[2];
},
set: function (value)
{
this.gl[2] = Math.min(Math.abs(value), 1);
this.b = Math.floor(this.gl[2] * 255);
this.update();
}
},
alphaGL: {
get: function ()
{
return this.gl[3];
},
set: function (value)
{
this.gl[3] = Math.min(Math.abs(value), 1);
this.a = Math.floor(this.gl[3] * 255);
this.update();
}
},
// Gets and sets the red value, normalized to the 0 to 255 range
red: {
get: function ()
{
return this.r;
},
set: function (value)
{
value = Math.floor(Math.abs(value));
this.r = Math.min(value, 255);
this.gl[0] = value / 255;
this.update();
}
},
green: {
get: function ()
{
return this.g;
},
set: function (value)
{
value = Math.floor(Math.abs(value));
this.g = Math.min(value, 255);
this.gl[1] = value / 255;
this.update();
}
},
blue: {
get: function ()
{
return this.b;
},
set: function (value)
{
value = Math.floor(Math.abs(value));
this.b = Math.min(value, 255);
this.gl[2] = value / 255;
this.update();
}
},
alpha: {
get: function ()
{
return this.a;
},
set: function (value)
{
value = Math.floor(Math.abs(value));
this.a = Math.min(value, 255);
this.gl[3] = value / 255;
this.update();
}
}
});
module.exports = Color;
| clark-stevenson/phaser | v3/src/graphics/color/Color.js | JavaScript | mit | 4,989 |
'use strict';
angular.module('app.controllers.invasiveness',[])
.controller('InvasivenessCtrl', ['$scope','ReferenceFactory', 'AncillaryDataFactory', function($scope,ReferenceFactory,AncillaryDataFactory) {
$scope.invasivenessAtomizedType = $scope.invasivenessFactoryLocal.invasivenessAtomizedType;
//Ancillary
var ancillaryDataFactoryUn = new AncillaryDataFactory();
$scope.ancillaryData = ancillaryDataFactoryUn.ancillaryData;
//reference unstructure
var referenceFactoryUn = new ReferenceFactory();
$scope.reference = referenceFactoryUn.reference;
//reference ato
var referenceFactoryAto = new ReferenceFactory();
$scope.referenceAto = referenceFactoryAto.reference;
//Ancillary
var ancillaryDataFactoryAto = new AncillaryDataFactory();
$scope.ancillaryDataAto = ancillaryDataFactoryAto.ancillaryData;
//Local variables for reset objects
var origI = angular.copy($scope.invasivenessAtomizedType);
var origR = angular.copy($scope.reference);
var origAD = angular.copy($scope.ancillaryData);
//list of lincese
$scope.lincese_list = angular.copy($scope.lenguajes.licences);
$scope.lincese_list_ato = angular.copy($scope.lenguajes.licences);
//list of proveedores de contenido
$scope.prov_contenido = angular.copy($scope.lenguajes.provContenido);
$scope.prov_contenido_ato = angular.copy($scope.lenguajes.provContenido);
$scope.checked = false; // This will be binded using the ps-open attribute
$scope.slide = function(){
$scope.checked = !$scope.checked;
};
$scope.checked_ato = false; // This will be binded using the ps-open attribute
$scope.slide_ato = function(){
$scope.checked_ato = !$scope.checked_ato;
};
$scope.addInvasiveness = function(){
if($scope.formData.invasiveness.invasivenessUnstructured !== ''){
console.log('enviar cambios');
}
};
$scope.addInvasivenessAtomizedType = function(list, invasiveness) {
if (JSON.stringify(invasiveness) !== JSON.stringify(origI)){
$scope.invasivenessFactoryLocal.add(list, invasiveness);
//Reset the scope variable
$scope.invasivenessAtomizedType = origI;
origI = angular.copy($scope.invasivenessAtomizedType);
$scope.UpdateCheckBoxes(invasiveness, false);
}
};
$scope.removeInvasivenessAtomized= function(list,invasiveness){
$scope.invasivenessFactoryLocal.delete(list,invasiveness);
};
$scope.editInvasivenessAtomized = function(list,invasiveness) {
$scope.invasivenessAtomizedType = angular.copy(invasiveness);
$scope.UpdateCheckBoxes(invasiveness, true);
};
$scope.cancelInvasivenessAtomizedType = function(invasiveness) {
$scope.invasivenessAtomizedType = angular.copy(origI);
$scope.UpdateCheckBoxes(invasiveness,false);
};
$scope.addAncillaryData = function(ancillaryDataList,ancillaryData){
if(ancillaryData.license !== ''){
var license = document.getElementById("ancillaryData.license");
if(license !== undefined && license!==null){
ancillaryData.license = license.value;
license.parentNode.removeChild(license);
}
ancillaryDataFactoryUn.addTo(ancillaryDataList,ancillaryData);
//Add all local reference to general reference vector
angular.forEach(ancillaryData.reference, function(reference) {
referenceFactoryLocal.addTo($scope.formData.references,reference);
});
//Reset the scope variable
$scope.ancillaryData = origAD;
origAD = angular.copy($scope.ancillaryData);
$scope.resetLicenseList(license,$scope.lincese_list);
$('#ancillaryInvasiveness').collapse("hide");
}else{
alert("La licencia debe ser seleccionada");
}
};
$scope.removeAncillaryData = function(ancillaryDataList,ancillaryData){
ancillaryDataFactoryUn.deleteFrom(ancillaryDataList,ancillaryData);
};
$scope.editAncillaryData = function(ancillaryDataList,ancillaryData) {
$scope.ancillaryData = angular.copy(ancillaryData);
var checked_almost_one = false;
angular.forEach($scope.lincese_list, function(item) {
if(ancillaryData.license!==null){
if(ancillaryData.license === item.nombre){
item.checked = true;
checked_almost_one = true;
}else{
item.checked = false;
if(item.nombre==='Otra' && !checked_almost_one){
if(document.getElementById('ancillaryData.license') === null){
item.checked = true;
var input = document.createElement("input");
input.type = "text";
input.id = "ancillaryData.license";
input.value = ancillaryData.license;
document.getElementById("ManualLicenseInvasivenessUn").appendChild(input);
}else{
var license = document.getElementById("ancillaryData.license");
license.value = ancillaryData.license;
}
}
}
}
});
$('#ancillaryInvasiveness').collapse("show");
};
$scope.cancelAncillaryData = function() {
$scope.ancillaryData = angular.copy(origAD);
var license = document.getElementById("ancillaryData.license");
$scope.resetLicenseList(license,$scope.lincese_list);
$('#ancillaryInvasiveness').collapse("hide");
};
$scope.findAncillary = function(ancillaryData){
angular.forEach($scope.formData.ancillaryData, function(ancillary) {
if(ancillaryData!==null && ancillaryData === ancillary.source){
$scope.ancillaryData = angular.copy(ancillary);
}
});
};
$scope.addReference = function(referenceList,reference){
if(reference.type !== ''){
referenceFactoryUn.addTo(referenceList,reference);
//Reset the scope variable
$scope.reference = origR;
origR = angular.copy($scope.reference);
$scope.checked = !$scope.checked;
}else{
alert("El tipo de referencia debe ser seleccionado");
}
};
$scope.removeReference = function(referenceList,reference){
referenceFactoryUn.deleteFrom(referenceList,reference);
};
$scope.editReference = function(referenceList,reference) {
$scope.reference = angular.copy(reference);
$scope.checked = !$scope.checked;
};
$scope.cancelReference = function() {
$scope.reference = angular.copy(origR);
$scope.checked = !$scope.checked;
};
//Atomized fields
$scope.addAncillaryDataAto = function(ancillaryDataList,ancillaryData){
if(ancillaryData.license !== ''){
var license = document.getElementById("ancillaryData.license");
if(license !== undefined && license!==null){
ancillaryData.license = license.value;
license.parentNode.removeChild(license);
}
ancillaryDataFactoryAto.addTo(ancillaryDataList,ancillaryData);
//Add all local reference to general reference vector
angular.forEach(ancillaryData.reference, function(reference) {
referenceFactoryLocal.addTo($scope.formData.references,reference);
});
//Reset the scope variable
$scope.ancillaryData = origAD;
origAD = angular.copy($scope.ancillaryData);
$scope.resetLicenseList(license,$scope.lincese_list_ato);
$('#ancillaryInvasivenessAto').collapse("hide");
}else{
alert("La licencia debe ser seleccionada");
}
};
$scope.editAncillaryDataAto = function(ancillaryDataList,ancillaryData) {
$scope.ancillaryDataAto = angular.copy(ancillaryData);
var checked_almost_one = false;
angular.forEach($scope.lincese_list_ato, function(item) {
if(ancillaryData.license!==null){
if(ancillaryData.license === item.nombre){
item.checked = true;
checked_almost_one = true;
}else{
item.checked = false;
if(item.nombre==='Otra' && !checked_almost_one){
if(document.getElementById('ancillaryData.license') === null){
item.checked = true;
var input = document.createElement("input");
input.type = "text";
input.id = "ancillaryData.license";
input.value = ancillaryData.license;
document.getElementById("ManualLicenseInvasivenessAto").appendChild(input);
}else{
var license = document.getElementById("ancillaryData.license");
license.value = ancillaryData.license;
}
}
}
}
});
$('#ancillaryInvasivenessAto').collapse("show");
};
$scope.cancelAncillaryDataAto = function() {
$scope.ancillaryDataAto = angular.copy(origAD);
var license = document.getElementById("ancillaryData.license");
$scope.resetLicenseList(license,$scope.lincese_list_ato);
$('#ancillaryInvasivenessAto').collapse("hide");
};
$scope.findAncillaryAto = function(ancillaryData){
angular.forEach($scope.formData.ancillaryData, function(ancillary) {
if(ancillaryData!==null && ancillaryData === ancillary.source){
$scope.ancillaryData = angular.copy(ancillary);
}
});
};
$scope.addReferenceAto = function(referenceList,reference){
if(reference.type !== ''){
referenceFactoryAto.addTo(referenceList,reference);
//Reset the scope variable
$scope.referenceAto = origR;
origR = angular.copy($scope.referenceAto);
$scope.checked_ato = !$scope.checked_ato;
}else{
alert("El tipo de referencia debe ser seleccionado");
}
};
$scope.editReferenceAto = function(referenceList,reference) {
$scope.referenceAto = angular.copy(reference);
$scope.checked_ato = !$scope.checked_ato;
};
$scope.cancelReferenceAto = function() {
$scope.referenceAto = angular.copy(origR);
$scope.checked_ato = !$scope.checked_ato;
};
$scope.findAncillaryAto = function(ancillaryData){
angular.forEach($scope.formData.ancillaryData, function(ancillary) {
if(ancillaryData!==null && ancillaryData === ancillary.source){
$scope.ancillaryDataAto = angular.copy(ancillary);
}
});
};
$scope.UpdateCheckBoxes = function(invasiveness,state){
angular.forEach($scope.lenguajes.origin, function(item) {
if(invasiveness.origin!==null && invasiveness.origin === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.presence, function(item) {
if(invasiveness.presence!==null && invasiveness.presence === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.persistence, function(item) {
if(invasiveness.persistence!==null && invasiveness.persistence === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.distribution, function(item) {
angular.forEach(invasiveness.distribution, function(distribution) {
if(distribution!==null && distribution === item.name){
item.checked = state;
}
});
});
angular.forEach($scope.lenguajes.harmful, function(item) {
if(invasiveness.harmful!==null && invasiveness.harmful === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.abundance, function(item) {
if(invasiveness.abundance!==null && invasiveness.abundance === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.trend, function(item) {
if(invasiveness.trend!==null && invasiveness.trend === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.rateOfSpread, function(item) {
if(invasiveness.rateOfSpread!==null && invasiveness.rateOfSpread === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.regulatoryListing, function(item) {
if(invasiveness.regulatoryListing!==null && invasiveness.regulatoryListing === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.localityType, function(item) {
if(invasiveness.localityType!==null && invasiveness.localityType === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.locationStandard, function(item) {
if(invasiveness.locationValue!==null && invasiveness.locationValue === item.name){
item.checked = state;
}
});
angular.forEach($scope.lenguajes.publicationDatePrecision, function(item) {
if(invasiveness.publicationDatePrecision!==null && invasiveness.publicationDatePrecision === item.name){
item.checked = state;
}
});
};
}]); | SIB-Colombia/mamut | src/public/javascripts/invasiveness/invasiveness.ctrl.js | JavaScript | mit | 12,178 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({"esri/widgets/Search/nls/Search":{widgetLabel:"Suche",searchButtonTitle:"Suchen",clearButtonTitle:"Suche l\u00f6schen",placeholder:"Adresse oder Ort suchen",searchIn:"Suchen in",all:"Alle",allPlaceholder:"Adresse oder Ort suchen",emptyValue:"Geben Sie einen Suchbegriff ein.",untitledResult:"Unbenannt",untitledSource:"Unbenannte Quelle",noResults:"Keine Ergebnisse",noResultsFound:"Es wurden keine Ergebnisse gefunden.",noResultsFoundForValue:"F\u00fcr {value} wurden keine Ergebnisse gefunden.",
showMoreResults:"Mehr Ergebnisse anzeigen",hideMoreResults:"Ausblenden",searchResult:"Suchergebnis",moreResultsHeader:"Mehr Ergebnisse",useCurrentLocation:"Aktuelle Position verwenden",_localized:{}},"esri/widgets/Attribution/nls/Attribution":{widgetLabel:"Quellennachweise",_localized:{}},"esri/widgets/Compass/nls/Compass":{widgetLabel:"Kompass",reset:"Kompassausrichtung zur\u00fccksetzen",_localized:{}},"esri/widgets/NavigationToggle/nls/NavigationToggle":{widgetLabel:"Navigationsumschaltung",toggle:"Zum Schwenken oder Drehen in 3D umschalten",
_localized:{}},"esri/widgets/Zoom/nls/Zoom":{widgetLabel:"Zoomen",zoomIn:"Vergr\u00f6\u00dfern",zoomOut:"Verkleinern",_localized:{}}}); | ycabon/presentations | 2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/widgets/nls/Search_de.js | JavaScript | mit | 1,350 |
"use strict";
const giveUniqueId = require("give-unique-id"),
q = require("q"),
dcConstants = require("dc-constants"),
MessageType = dcConstants.MessageType;
function ChooseOwnCar($player) {
giveUniqueId(this);
let self = this;
let player = $player;
$player = null;
let callbacks, deferred;
function handleIt(cb) {
callbacks = cb;
let msg = {
cmd: MessageType.ChooseOwnCar,
playerId: player.id,
handlerId: self.id
};
callbacks.broadcast("action", msg);
deferred = q.defer();
return deferred.promise;
}
this.handleIt = handleIt;
function giveAnswer(answeringPlayer, answer) {
if(answeringPlayer !== player) return;
if(!validateAnswer(answer)) return;
deferred.resolve(player.cars[answer.carId]);
}
this.giveAnswer = giveAnswer;
function validateAnswer(answer) {
return answer.carId in player.cars;
}
}
module.exports = ChooseOwnCar; | ryb73/dealers-choice-meta | packages/server/lib/game-managers/choice-provider/choose-own-car.js | JavaScript | mit | 957 |
(function(){
"use strict";
angular
.module('skitter')
.controller('skitterCtrl', skitterCtrl);
skitterCtrl.$inject = ['$scope'];
function skitterCtrl ($scope) {
$scope.photos = [
{
src: 'https://skitterp-4b51.kxcdn.com/images/mountains/3-sand-mountain-clouds.jpg',
title: 'Donec sollicitudin molestie',
description: 'Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie malesuada.',
url: 'http://www.google.com'
},
{
src: 'https://skitterp-4b51.kxcdn.com/images/mountains/4-landscape-with-tree-hills-and-lake.jpg',
title: 'Vivamus suscipit tortor',
description: 'Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie malesuada.',
url: 'http://www.facebook.com'
},
{
src: 'https://skitterp-4b51.kxcdn.com/images/mountains/2-utah-mountain-sky-nature-golden-hour-sunset.jpg',
title: 'Ttortor eget felis porttitor',
description: 'Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie malesuada.',
url: 'http://www.linkedin.com'
}
];
$scope.skitterOption = {
auto_play: false,
theme: "clean",
navigation: true,
animation: "cubeShow",
dots: true
}
};
})();
| kinotto/angular-skitter | github-page/skitter.controller.js | JavaScript | mit | 1,534 |
var path = require('path');
var del = require('del');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
// set variable via $ gulp --type production
var environment = $.util.env.type || 'development';
var isProduction = environment === 'production';
var webpackConfig = require('./webpack.config.js').getConfig(environment);
var port = $.util.env.port || 1337;
var app = 'app/';
var dist = 'dist/';
// https://github.com/ai/autoprefixer
var autoprefixerBrowsers = [
'ie >= 9',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 6',
'opera >= 23',
'ios >= 6',
'android >= 4.4',
'bb >= 10'
];
gulp.task('scripts', function() {
return gulp.src(webpackConfig.entry)
.pipe($.webpack(webpackConfig))
.pipe(isProduction ? $.uglify() : $.util.noop())
.pipe(gulp.dest(dist + 'js/'))
.pipe($.size({ title : 'js' }))
.pipe($.connect.reload());
});
// copy html from app to dist
gulp.task('html', function() {
return gulp.src(app + 'index.html')
.pipe(gulp.dest(dist))
.pipe($.size({ title : 'html' }))
.pipe($.connect.reload());
});
gulp.task('styles',function(cb) {
// build css styles
return gulp.src(app + 'sass/main.scss')
.pipe($.sass())
.pipe($.autoprefixer({browsers: autoprefixerBrowsers}))
.pipe(gulp.dest(dist + 'css/'))
.pipe($.size({ title : 'css' }))
.pipe($.connect.reload());
});
// add livereload on the given port
gulp.task('serve', function() {
$.connect.server({
root: dist,
port: port,
livereload: {
port: 35729
}
});
});
// copy images
gulp.task('images', function(cb) {
return gulp.src(app + 'images/**/*.{png,jpg,jpeg,gif}')
.pipe($.size({ title : 'images' }))
.pipe(gulp.dest(dist + 'images/'));
});
// watch styl, html and js file changes
gulp.task('watch', function() {
gulp.watch(app + 'sass/*.scss', ['styles']);
gulp.watch(app + 'index.html', ['html']);
gulp.watch(app + 'scripts/**/*.js', ['scripts']);
gulp.watch(app + 'scripts/**/*.jsx', ['scripts']);
});
// remove bundels
gulp.task('clean', function(cb) {
return del([dist], cb);
});
// by default build project and then watch files in order to trigger livereload
gulp.task('default', ['images', 'html','scripts', 'styles', 'serve', 'watch']);
// waits until clean is finished then builds the project
gulp.task('build', ['clean'], function(){
gulp.start(['images', 'html', 'scripts', 'styles']);
});
| redcrazyheart/weather | gulpfile.js | JavaScript | mit | 2,436 |
/**
* Command parser
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This is the command parser. Call it with CommandParser.parse
* (scroll down to its definition for details)
*
* Individual commands are put in:
* commands.js - "core" commands that shouldn't be modified
* chat-plugins/ - other commands that can be safely modified
*
* The command API is (mostly) documented in chat-plugins/COMMANDS.md
*
* @license MIT license
*/
/*
To reload chat commands:
/hotpatch chat
*/
const MAX_MESSAGE_LENGTH = 300;
const BROADCAST_COOLDOWN = 20 * 1000;
const MESSAGE_COOLDOWN = 5 * 60 * 1000;
const MAX_PARSE_RECURSION = 10;
const VALID_COMMAND_TOKENS = '/!';
const BROADCAST_TOKEN = '!';
var fs = require('fs');
var path = require('path');
var parseEmoticons = require('./chat-plugins/emoticons').parseEmoticons;
/*********************************************************
* Load command files
*********************************************************/
var baseCommands = exports.baseCommands = require('./commands.js').commands;
var commands = exports.commands = Object.clone(baseCommands);
// Install plug-in commands
// info always goes first so other plugins can shadow it
Object.merge(commands, require('./chat-plugins/info.js').commands);
fs.readdirSync(path.resolve(__dirname, 'chat-plugins')).forEach(function (file) {
if (file.substr(-3) !== '.js' || file === 'info.js') return;
Object.merge(commands, require('./chat-plugins/' + file).commands);
});
/*********************************************************
* Modlog
*********************************************************/
var modlog = exports.modlog = {
lobby: fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_lobby.txt'), {flags:'a+'}),
battle: fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_battle.txt'), {flags:'a+'})
};
var writeModlog = exports.writeModlog = function (roomid, text) {
if (!modlog[roomid]) {
modlog[roomid] = fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_' + roomid + '.txt'), {flags:'a+'});
}
modlog[roomid].write('[' + (new Date().toJSON()) + '] ' + text + '\n');
};
/*********************************************************
* Parser
*********************************************************/
/**
* Can this user talk?
* Shows an error message if not.
*/
function canTalk(user, room, connection, message, targetUser) {
if (!user.named) {
connection.popup("You must choose a name before you can talk.");
return false;
}
if (room && user.locked) {
connection.sendTo(room, "You are locked from talking in chat.");
return false;
}
if (room && room.isMuted(user)) {
connection.sendTo(room, "You are muted and cannot talk in this room.");
return false;
}
if (room && room.modchat) {
if (room.modchat === 'crash') {
if (!user.can('ignorelimits')) {
connection.sendTo(room, "Because the server has crashed, you cannot speak in lobby chat.");
return false;
}
} else {
var userGroup = user.group;
if (room.auth) {
if (room.auth[user.userid]) {
userGroup = room.auth[user.userid];
} else if (room.isPrivate === true) {
userGroup = ' ';
}
}
if (room.modchat === 'autoconfirmed') {
if (!user.autoconfirmed && userGroup === ' ') {
connection.sendTo(room, "Because moderated chat is set, your account must be at least one week old and you must have won at least one ladder game to speak in this room.");
return false;
}
} else if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(room.modchat) && !user.can('bypassall')) {
var groupName = Config.groups[room.modchat].name || room.modchat;
connection.sendTo(room, "Because moderated chat is set, you must be of rank " + groupName + " or higher to speak in this room.");
return false;
}
}
}
if (room && !(user.userid in room.users)) {
connection.popup("You can't send a message to this room without being in it.");
return false;
}
if (typeof message === 'string') {
if (!message) {
connection.popup("Your message can't be blank.");
return false;
}
if (message.length > MAX_MESSAGE_LENGTH && !user.can('ignorelimits')) {
connection.popup("Your message is too long:\n\n" + message);
return false;
}
// remove zalgo
message = message.replace(/[\u0300-\u036f\u0483-\u0489\u064b-\u065f\u0670\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '');
if (room && room.id === 'lobby') {
var normalized = message.trim();
if ((normalized === user.lastMessage) &&
((Date.now() - user.lastMessageTime) < MESSAGE_COOLDOWN)) {
connection.popup("You can't send the same message again so soon.");
return false;
}
user.lastMessage = message;
user.lastMessageTime = Date.now();
}
if (Config.chatfilter) {
return Config.chatfilter.call(this, message, user, room, connection, targetUser);
}
return message;
}
return true;
}
var Context = exports.Context = (function () {
function Context(options) {
this.cmd = options.cmd || '';
this.cmdToken = options.cmdToken || '';
this.target = options.target || '';
this.message = options.message || '';
this.levelsDeep = options.levelsDeep || 0;
this.namespaces = options.namespaces || null;
this.room = options.room || null;
this.user = options.user || null;
this.connection = options.connection || null;
this.targetUserName = '';
this.targetUser = null;
}
Context.prototype.sendReply = function (data) {
if (this.broadcasting) {
this.room.add(data);
} else {
this.connection.sendTo(this.room, data);
}
};
Context.prototype.errorReply = function (message) {
if (this.pmTarget) {
this.connection.send('|pm|' + this.user.getIdentity() + '|' + (this.pmTarget.getIdentity ? this.pmTarget.getIdentity() : ' ' + this.pmTarget) + '|/error ' + message);
} else {
this.connection.sendTo(this.room, '|html|<div class="message-error">' + Tools.escapeHTML(message) + '</div>');
}
};
Context.prototype.sendReplyBox = function (html) {
this.sendReply('|raw|<div class="infobox">' + html + '</div>');
};
Context.prototype.popupReply = function (message) {
this.connection.popup(message);
};
Context.prototype.add = function (data) {
this.room.add(data);
};
Context.prototype.send = function (data) {
this.room.send(data);
};
Context.prototype.privateModCommand = function (data, noLog) {
this.sendModCommand(data);
this.logEntry(data);
this.logModCommand(data);
};
Context.prototype.sendModCommand = function (data) {
var users = this.room.users;
var auth = this.room.auth;
for (var i in users) {
var user = users[i];
// hardcoded for performance reasons (this is an inner loop)
if (user.isStaff || (auth && (auth[user.userid] || '+') !== '+')) {
user.sendTo(this.room, data);
}
}
};
Context.prototype.logEntry = function (data) {
this.room.logEntry(data);
};
Context.prototype.addModCommand = function (text, logOnlyText) {
this.add(text);
this.logModCommand(text + (logOnlyText || ""));
};
Context.prototype.logModCommand = function (text) {
var roomid = (this.room.battle ? 'battle' : this.room.id);
writeModlog(roomid, '(' + this.room.id + ') ' + text);
};
Context.prototype.globalModlog = function (action, user, text) {
var buf = "(" + this.room.id + ") " + action + ": ";
if (typeof user === 'string') {
buf += "[" + toId(user) + "]";
} else {
var userid = this.getLastIdOf(user);
buf += "[" + userid + "]";
if (user.autoconfirmed && user.autoconfirmed !== userid) buf += " ac:[" + user.autoconfirmed + "]";
}
buf += text;
writeModlog('global', buf);
};
Context.prototype.can = function (permission, target, room) {
if (!this.user.can(permission, target, room)) {
this.errorReply(this.cmdToken + this.namespaces.concat(this.cmd).join(" ") + " - Access denied.");
return false;
}
return true;
};
Context.prototype.canBroadcast = function (suppressMessage) {
if (!this.broadcasting && this.cmdToken === BROADCAST_TOKEN) {
var message = this.canTalk(this.message);
if (!message) return false;
if (!this.user.can('broadcast', null, this.room)) {
this.errorReply("You need to be voiced to broadcast this command's information.");
this.errorReply("To see it for yourself, use: /" + message.substr(1));
return false;
}
// broadcast cooldown
var normalized = message.toLowerCase().replace(/[^a-z0-9\s!,]/g, '');
if (this.room.lastBroadcast === normalized &&
this.room.lastBroadcastTime >= Date.now() - BROADCAST_COOLDOWN) {
this.errorReply("You can't broadcast this because it was just broadcast.");
return false;
}
this.add('|c|' + this.user.getIdentity(this.room.id) + '|' + (suppressMessage || message));
this.room.lastBroadcast = normalized;
this.room.lastBroadcastTime = Date.now();
this.broadcasting = true;
}
return true;
};
Context.prototype.parse = function (message, inNamespace) {
if (inNamespace && this.cmdToken) {
message = this.cmdToken + this.namespaces.concat(message.slice(1)).join(" ");
}
return CommandParser.parse(message, this.room, this.user, this.connection, this.levelsDeep + 1);
};
Context.prototype.run = function (targetCmd, inNamespace) {
var commandHandler;
if (typeof targetCmd === 'function') {
commandHandler = targetCmd;
} else if (inNamespace) {
commandHandler = commands;
for (var i = 0; i < this.namespaces.length; i++) {
commandHandler = commandHandler[this.namespaces[i]];
}
commandHandler = commandHandler[targetCmd];
} else {
commandHandler = commands[targetCmd];
}
var result;
try {
result = commandHandler.call(this, this.target, this.room, this.user, this.connection, this.cmd, this.message);
} catch (err) {
var stack = err.stack + '\n\n' +
'Additional information:\n' +
'user = ' + this.user.name + '\n' +
'room = ' + this.room.id + '\n' +
'message = ' + this.message;
var fakeErr = {stack: stack};
if (!require('./crashlogger.js')(fakeErr, 'A chat command')) {
var ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />");
if (Rooms.lobby) Rooms.lobby.send('|html|<div class="broadcast-red"><b>POKEMON SHOWDOWN HAS CRASHED:</b> ' + ministack + '</div>');
} else {
this.sendReply('|html|<div class="broadcast-red"><b>Pokemon Showdown crashed!</b><br />Don\'t worry, we\'re working on fixing it.</div>');
}
}
if (result === undefined) result = false;
return result;
};
Context.prototype.canTalk = function (message, relevantRoom, targetUser) {
var innerRoom = (relevantRoom !== undefined) ? relevantRoom : this.room;
return canTalk.call(this, this.user, innerRoom, this.connection, message, targetUser);
};
Context.prototype.canHTML = function (html) {
html = '' + (html || '');
var images = html.match(/<img\b[^<>]*/ig);
if (!images) return true;
for (var i = 0; i < images.length; i++) {
if (!/width=([0-9]+|"[0-9]+")/i.test(images[i]) || !/height=([0-9]+|"[0-9]+")/i.test(images[i])) {
this.errorReply('All images must have a width and height attribute');
return false;
}
}
if (/>here.?</i.test(html) || /click here/i.test(html)) {
this.errorReply('Do not use "click here"');
return false;
}
// check for mismatched tags
var tags = html.toLowerCase().match(/<\/?(div|a|button|b|i|u|center|font)\b/g);
if (tags) {
var stack = [];
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.charAt(1) === '/') {
if (!stack.length) {
this.errorReply("Extraneous </" + tag.substr(2) + "> without an opening tag.");
return false;
}
if (tag.substr(2) !== stack.pop()) {
this.errorReply("Missing </" + tag.substr(2) + "> or it's in the wrong place.");
return false;
}
} else {
stack.push(tag.substr(1));
}
}
if (stack.length) {
this.errorReply("Missing </" + stack.pop() + ">.");
return false;
}
}
return true;
};
Context.prototype.targetUserOrSelf = function (target, exactName) {
if (!target) {
this.targetUsername = this.user.name;
this.inputUsername = this.user.name;
return this.user;
}
this.splitTarget(target, exactName);
return this.targetUser;
};
Context.prototype.getLastIdOf = function (user) {
if (typeof user === 'string') user = Users.get(user);
return (user.named ? user.userid : (Object.keys(user.prevNames).last() || user.userid));
};
Context.prototype.splitTarget = function (target, exactName) {
var commaIndex = target.indexOf(',');
if (commaIndex < 0) {
var targetUser = Users.get(target, exactName);
this.targetUser = targetUser;
this.inputUsername = target.trim();
this.targetUsername = targetUser ? targetUser.name : target;
return '';
}
this.inputUsername = target.substr(0, commaIndex);
var targetUser = Users.get(this.inputUsername, exactName);
if (targetUser) {
this.targetUser = targetUser;
this.targetUsername = this.inputUsername = targetUser.name;
} else {
this.targetUser = null;
this.targetUsername = this.inputUsername;
}
return target.substr(commaIndex + 1).trim();
};
return Context;
})();
/**
* Command parser
*
* Usage:
* CommandParser.parse(message, room, user, connection)
*
* message - the message the user is trying to say
* room - the room the user is trying to say it in
* user - the user that sent the message
* connection - the connection the user sent the message from
*
* Returns the message the user should say, or a falsy value which
* means "don't say anything"
*
* Examples:
* CommandParser.parse("/join lobby", room, user, connection)
* will make the user join the lobby, and return false.
*
* CommandParser.parse("Hi, guys!", room, user, connection)
* will return "Hi, guys!" if the user isn't muted, or
* if he's muted, will warn him that he's muted, and
* return false.
*/
var parse = exports.parse = function (message, room, user, connection, levelsDeep) {
var cmd = '', target = '', cmdToken = '';
if (!message || !message.trim().length) return;
if (!levelsDeep) {
levelsDeep = 0;
} else {
if (levelsDeep > MAX_PARSE_RECURSION) {
return connection.sendTo(room, "Error: Too much recursion");
}
}
if (message.substr(0, 3) === '>> ') {
// multiline eval
message = '/eval ' + message.substr(3);
} else if (message.substr(0, 4) === '>>> ') {
// multiline eval
message = '/evalbattle ' + message.substr(4);
}
if (VALID_COMMAND_TOKENS.includes(message.charAt(0)) && message.charAt(1) !== message.charAt(0)) {
cmdToken = message.charAt(0);
var spaceIndex = message.indexOf(' ');
if (spaceIndex > 0) {
cmd = message.substr(1, spaceIndex - 1).toLowerCase();
target = message.substr(spaceIndex + 1);
} else {
cmd = message.substr(1).toLowerCase();
target = '';
}
}
var namespaces = [];
var currentCommands = commands;
var commandHandler;
do {
commandHandler = currentCommands[cmd];
if (typeof commandHandler === 'string') {
// in case someone messed up, don't loop
commandHandler = currentCommands[commandHandler];
}
if (commandHandler && typeof commandHandler === 'object') {
namespaces.push(cmd);
var spaceIndex = target.indexOf(' ');
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex).toLowerCase();
target = target.substr(spaceIndex + 1);
} else {
cmd = target.toLowerCase();
target = '';
}
currentCommands = commandHandler;
}
} while (commandHandler && typeof commandHandler === 'object');
if (!commandHandler && currentCommands.default) {
commandHandler = currentCommands.default;
if (typeof commandHandler === 'string') {
commandHandler = currentCommands[commandHandler];
}
}
var fullCmd = namespaces.concat(cmd).join(' ');
var context = new Context({
target: target, room: room, user: user, connection: connection, cmd: cmd, message: message,
namespaces: namespaces, cmdToken: cmdToken, levelsDeep: levelsDeep
});
if (commandHandler) {
return context.run(commandHandler);
} else {
// Check for mod/demod/admin/deadmin/etc depending on the group ids
for (var g in Config.groups) {
var groupid = Config.groups[g].id;
if (cmd === groupid || cmd === 'global' + groupid) {
return parse('/promote ' + toId(target) + ', ' + g, room, user, connection, levelsDeep + 1);
} else if (cmd === 'de' + groupid || cmd === 'un' + groupid || cmd === 'globalde' + groupid || cmd === 'deglobal' + groupid) {
return parse('/demote ' + toId(target), room, user, connection, levelsDeep + 1);
} else if (cmd === 'room' + groupid) {
return parse('/roompromote ' + toId(target) + ', ' + g, room, user, connection, levelsDeep + 1);
} else if (cmd === 'roomde' + groupid || cmd === 'deroom' + groupid || cmd === 'roomun' + groupid) {
return parse('/roomdemote ' + toId(target), room, user, connection, levelsDeep + 1);
}
}
if (cmdToken && fullCmd) {
// To guard against command typos, we now emit an error message
if (cmdToken === BROADCAST_TOKEN) {
if (/[a-z0-9]/.test(cmd.charAt(0))) {
return context.errorReply("The command '" + cmdToken + fullCmd + "' was unrecognized.");
}
} else {
return context.errorReply("The command '" + cmdToken + fullCmd + "' was unrecognized. To send a message starting with '" + cmdToken + fullCmd + "', type '" + cmdToken.repeat(2) + fullCmd + "'.");
}
} else if (!VALID_COMMAND_TOKENS.includes(message.charAt(0)) && VALID_COMMAND_TOKENS.includes(message.trim().charAt(0))) {
message = message.trim();
if (message.charAt(0) !== BROADCAST_TOKEN) {
message = message.charAt(0) + message;
}
}
}
message = canTalk.call(context, user, room, connection, message);
if (parseEmoticons(message, room, user)) return;
return message || false;
};
exports.package = {};
fs.readFile(path.resolve(__dirname, 'package.json'), function (err, data) {
if (err) return;
exports.package = JSON.parse(data);
});
exports.uncacheTree = function (root) {
var uncache = [require.resolve(root)];
do {
var newuncache = [];
for (var i = 0; i < uncache.length; ++i) {
if (require.cache[uncache[i]]) {
newuncache.push.apply(newuncache,
require.cache[uncache[i]].children.map('id')
);
delete require.cache[uncache[i]];
}
}
uncache = newuncache;
} while (uncache.length > 0);
};
| DarkSuicune/Kakuja-2.0 | command-parser.js | JavaScript | mit | 18,395 |
import React from 'react';
import { shallow } from 'enzyme';
import { Div } from 'glamorous';
import Card from '../../app/components/Card';
describe('Card', () => {
const TitleComponent = () => (<div>Title</div>);
const children = <div>Children</div>;
const result = shallow(
<Card TitleComponent={TitleComponent}>
{children}
</Card>
);
it('should initally be closed', () => {
expect(result.state('expanded')).toBe(false);
expect(result).toMatchSnapshot();
});
it('should open once the title is clicked', () => {
result.find(Div).simulate('click');
expect(result.state('expanded')).toBe(true);
expect(result).toMatchSnapshot();
});
it('should close if the title is clickedAgain', () => {
result.find(Div).simulate('click');
expect(result.state('expanded')).toBe(false);
expect(result).toMatchSnapshot();
});
});
| Byte-Code/lm-digital-store-private-test | test/components/Card.spec.js | JavaScript | mit | 883 |
import cx from 'classnames'
import React, { PropTypes } from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* Show a feed date
*/
function FeedDate(props) {
const { children, className, content } = props
const classes = cx(className, 'date')
const rest = getUnhandledProps(FeedDate, props)
const ElementType = getElementType(FeedDate, props)
return <ElementType {...rest} className={classes}>{children || content}</ElementType>
}
FeedDate._meta = {
name: 'FeedDate',
parent: 'Feed',
type: META.TYPES.VIEW,
}
FeedDate.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default FeedDate
| ben174/Semantic-UI-React | src/views/Feed/FeedDate.js | JavaScript | mit | 927 |
const visit = require('unist-util-visit')
module.exports = ({ markdownAST }) => {
visit(markdownAST, 'link', node => {
node.url = node.url.replace(/^https?:\/\/emotion.sh/, '')
if (!node.url.startsWith('//') && !node.url.startsWith('http')) {
node.url = node.url
.replace(/\.mdx?(#.*)?$/, (match, hash) => {
return hash || ''
})
.replace(/^\/packages\//, '/docs/@emotion/')
}
})
}
| tkh44/emotion | site/plugins/gatsby-remark-fix-links/index.js | JavaScript | mit | 438 |
import React, { Component } from 'react';
import { LinksTabBar } from './lib/links-tabbar';
import { LinkPreview } from './lib/link-detail-preview';
import { SidebarSwitcher } from '/components/lib/icons/icon-sidebar-switch.js';
import { api } from '../api';
import { Link } from 'react-router-dom';
import { Comments } from './lib/comments';
import { Spinner } from './lib/icons/icon-spinner';
import { LoadingScreen } from './loading';
import { makeRoutePath, getContactDetails } from '../lib/util';
import CommentItem from './lib/comment-item';
export class LinkDetail extends Component {
constructor(props) {
super(props);
this.state = {
comment: '',
data: props.data,
commentFocus: false,
pending: new Set(),
disabled: false
};
this.setComment = this.setComment.bind(this);
}
updateData(submission) {
this.setState({
data: submission
});
}
componentDidMount() {
// if we have no preloaded data, and we aren't expecting it, get it
if (!this.state.data.title) {
api.getSubmission(
this.props.resourcePath, this.props.url, this.updateData.bind(this)
);
}
}
componentDidUpdate(prevProps) {
if (this.props.url !== prevProps.url) {
this.updateData(this.props.data);
}
if (prevProps.comments && prevProps.comments['0'] &&
this.props.comments && this.props.comments['0']) {
const prevFirstComment = prevProps.comments['0'][0];
const thisFirstComment = this.props.comments['0'][0];
if ((prevFirstComment && prevFirstComment.udon) &&
(thisFirstComment && thisFirstComment.udon)) {
if (this.state.pending.has(thisFirstComment.udon)) {
const pending = this.state.pending;
pending.delete(thisFirstComment.udon);
this.setState({
pending: pending
});
}
}
}
}
onClickPost() {
const url = this.props.url || '';
const pending = this.state.pending;
pending.add(this.state.comment);
this.setState({ pending: pending, disabled: true });
api.postComment(
this.props.resourcePath,
url,
this.state.comment
).then(() => {
this.setState({ comment: '', disabled: false });
});
}
setComment(event) {
this.setState({ comment: event.target.value });
}
render() {
const props = this.props;
const data = this.state.data || props.data;
if (!data.ship) {
return <LoadingScreen />;
}
const ship = data.ship || 'zod';
const title = data.title || '';
const url = data.url || '';
const commentCount = props.comments
? props.comments.totalItems
: data.commentCount || 0;
const comments = commentCount + ' comment' + (commentCount === 1 ? '' : 's');
const { nickname } = getContactDetails(props.contacts[ship]);
const activeClasses = this.state.comment
? 'black white-d pointer'
: 'gray2 b--gray2';
const focus = (this.state.commentFocus)
? 'b--black b--white-d'
: 'b--gray4 b--gray2-d';
const our = getContactDetails(props.contacts[window.ship]);
const pendingArray = Array.from(this.state.pending).map((com, i) => {
return(
<CommentItem
key={i}
color={our.color}
nickname={our.nickname}
ship={window.ship}
pending={true}
content={com}
member={our.member}
time={new Date().getTime()}
/>
);
});
return (
<div className="h-100 w-100 overflow-hidden flex flex-column">
<div
className={'pl4 pt2 flex relative overflow-x-scroll ' +
'overflow-x-auto-l overflow-x-auto-xl flex-shrink-0 ' +
'bb bn-m bn-l bn-xl b--gray4'}
style={{ height: 48 }}
>
<SidebarSwitcher
sidebarShown={props.sidebarShown}
popout={props.popout}
/>
<Link
className="dib f9 fw4 pt2 gray2 lh-solid"
to={makeRoutePath(props.resourcePath, props.popout, props.page)}
>
{`<- ${props.resource.metadata.title}`}
</Link>
<LinksTabBar {...props} popout={props.popout} resourcePath={props.resourcePath} />
</div>
<div className="w-100 mt2 flex justify-center overflow-y-scroll ph4 pb4">
<div className="w-100 mw7">
<LinkPreview
title={title}
url={url}
comments={comments}
nickname={nickname}
ship={ship}
resourcePath={props.resourcePath}
page={props.page}
linkIndex={props.linkIndex}
time={this.state.data.time}
/>
<div className="relative">
<div className={'relative ba br1 mt6 mb6 ' + focus}>
<textarea
className="w-100 bg-gray0-d white-d f8 pa2 pr8"
style={{
resize: 'none',
height: 75
}}
placeholder="Leave a comment on this link"
onChange={this.setComment}
onKeyDown={(e) => {
if (
(e.getModifierState('Control') || e.metaKey) &&
e.key === 'Enter'
) {
this.onClickPost();
}
}}
onFocus={() => this.setState({ commentFocus: true })}
onBlur={() => this.setState({ commentFocus: false })}
value={this.state.comment}
/>
<button
className={
'f8 bg-gray0-d ml2 absolute ' + activeClasses
}
disabled={!this.state.comment || this.state.disabled}
onClick={this.onClickPost.bind(this)}
style={{
bottom: 12,
right: 8
}}
>
Post
</button>
</div>
<Spinner awaiting={this.state.disabled} classes="absolute pt5 right-0" text="Posting comment..." />
{pendingArray}
</div>
<Comments
resourcePath={props.resourcePath}
key={props.resourcePath + props.commentPage}
comments={props.comments}
commentPage={props.commentPage}
contacts={props.contacts}
popout={props.popout}
url={props.url}
linkPage={props.page}
linkIndex={props.linkIndex}
/>
</div>
</div>
</div>
);
}
}
export default LinkDetail;
| ngzax/urbit | pkg/interface/link/src/js/components/link.js | JavaScript | mit | 6,784 |
version https://git-lfs.github.com/spec/v1
oid sha256:7d1521bd1f026b82cddfd0aee18c88f8a5fcc971648e199e4996de3d86713dc4
size 26006
| yogeshsaroya/new-cdnjs | ajax/libs/jquery.nanoscroller/0.8.2/javascripts/jquery.nanoscroller.js | JavaScript | mit | 130 |
declare module "react-native-qrcode-svg" {
declare export type ImageSourcePropType = number | { uri: string, ... };
declare export type QRCodeSvgProps = {
/* what the qr code stands for */
value?: string,
/* the whole component size */
size?: number,
/* the color of the cell */
color?: string,
/* the color of the background */
backgroundColor?: string,
/* an image source object. example {uri: 'base64string'} or {require('pathToImage')} */
logo?: ImageSourcePropType,
/* logo size in pixels */
logoSize?: number,
/* the logo gets a filled rectangular background with this color. Use 'transparent'
if your logo already has its own backdrop. Default = same as backgroundColor */
logoBackgroundColor?: string,
/* logo's distance to its wrapper */
logoMargin?: number,
/* the border-radius of logo image */
logoBorderRadius?: number,
/* get svg ref for further usage */
getRef?: (ref: any) => void,
/* error correction level */
ecl?: "L" | "M" | "Q" | "H",
...
};
declare class QRCodeSvg extends React$PureComponent<QRCodeSvgProps> {}
declare export default typeof QRCodeSvg;
}
| splodingsocks/FlowTyped | definitions/npm/react-native-qrcode-svg_v5.x.x/flow_v0.104.x-/react-native-qrcode-svg_v5.x.x.js | JavaScript | mit | 1,193 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 13c0 .55-.45 1-1 1H5c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v10zm-6-7c.55 0 1-.45 1-1s-.45-1-1-1h-1v-.01c0-.55-.45-1-1-1s-1 .45-1 1V8h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1h-3c-.55 0-1 .45-1 1s.45 1 1 1h1c0 .55.45 1 1 1s1-.45 1-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h3z"
}), 'LocalAtmRounded'); | oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/LocalAtmRounded.js | JavaScript | mit | 573 |
var turboMod = function turboMod (a, b) {
return a % b;
};
anything.prototype.turboMod = turboMod;
| Sha-Grisha/anything.js | src/turboMod.js | JavaScript | mit | 103 |
export default function() {
throw new Error(`
As of v7.0.0-beta.55, we've removed Babel's Stage presets.
Please consider reading our blog post on this decision at
https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
for more details. TL;DR is that it's more beneficial in the
long run to explicitly add which proposals to use.
For a more automatic migration, we have updated babel-upgrade,
https://github.com/babel/babel-upgrade to do this for you with
"npx babel-upgrade".
If you want the same configuration as before:
{
"plugins": [
// Stage 1
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-logical-assignment-operators",
["@babel/plugin-proposal-optional-chaining", { "loose": false }],
["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }],
["@babel/plugin-proposal-nullish-coalescing-operator", { "loose": false }],
"@babel/plugin-proposal-do-expressions",
// Stage 2
["@babel/plugin-proposal-decorators", { "legacy": true }],
"@babel/plugin-proposal-function-sent",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-throw-expressions",
// Stage 3
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-import-meta",
["@babel/plugin-proposal-class-properties", { "loose": false }],
"@babel/plugin-proposal-json-strings"
]
}
If you're using the same configuration across many separate projects,
keep in mind that you can also create your own custom presets with
whichever plugins and presets you're looking to use.
module.exports = function() {
return {
plugins: [
require("@babel/plugin-syntax-dynamic-import"),
[require("@babel/plugin-proposal-decorators"), { "legacy": true }],
[require("@babel/plugin-proposal-class-properties"), { "loose": false }],
],
presets: [
// ...
],
};
};
`);
}
| Skillupco/babel | packages/babel-preset-stage-1/src/index.js | JavaScript | mit | 1,951 |
/**
* lscache library
* Copyright (c) 2011, Pamela Fox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint undef:true, browser:true */
/**
* Creates a namespace for the lscache functions.
*/
var lscache = function() {
// Prefix for all lscache keys
var CACHE_PREFIX = 'lscache-';
// Suffix for the key name on the expiration items in localStorage
var CACHE_SUFFIX = '-cacheexpiration';
// expiration date radix (set to Base-36 for most space savings)
var EXPIRY_RADIX = 10;
// time resolution in minutes
var EXPIRY_UNITS = 60 * 1000;
// ECMAScript max Date (epoch + 1e8 days)
var MAX_DATE = Math.floor(8.64e15/EXPIRY_UNITS);
var cachedStorage;
var cachedJSON;
var cacheBucket = '';
// Determines if localStorage is supported in the browser;
// result is cached for better performance instead of being run each time.
// Feature detection is based on how Modernizr does it;
// it's not straightforward due to FF4 issues.
// It's not run at parse-time as it takes 200ms in Android.
function supportsStorage() {
var key = '__lscachetest__';
var value = key;
if (cachedStorage !== undefined) {
return cachedStorage;
}
try {
setItem(key, value);
removeItem(key);
cachedStorage = true;
} catch (exc) {
cachedStorage = false;
}
return cachedStorage;
}
// Determines if native JSON (de-)serialization is supported in the browser.
function supportsJSON() {
/*jshint eqnull:true */
if (cachedJSON === undefined) {
cachedJSON = (window.JSON != null);
}
return cachedJSON;
}
/**
* Returns the full string for the localStorage expiration item.
* @param {String} key
* @return {string}
*/
function expirationKey(key) {
return key + CACHE_SUFFIX;
}
/**
* Returns the number of minutes since the epoch.
* @return {number}
*/
function currentTime() {
return Math.floor((new Date().getTime())/EXPIRY_UNITS);
}
/**
* Wrapper functions for localStorage methods
*/
function getItem(key) {
return localStorage.getItem(CACHE_PREFIX + cacheBucket + key);
}
function setItem(key, value) {
// Fix for iPad issue - sometimes throws QUOTA_EXCEEDED_ERR on setItem.
localStorage.removeItem(CACHE_PREFIX + cacheBucket + key);
localStorage.setItem(CACHE_PREFIX + cacheBucket + key, value);
}
function removeItem(key) {
localStorage.removeItem(CACHE_PREFIX + cacheBucket + key);
}
return {
/**
* Stores the value in localStorage. Expires after specified number of minutes.
* @param {string} key
* @param {Object|string} value
* @param {number} time
*/
set: function(key, value, time) {
if (!supportsStorage()) return;
// If we don't get a string value, try to stringify
// In future, localStorage may properly support storing non-strings
// and this can be removed.
if (typeof value !== 'string') {
if (!supportsJSON()) return;
try {
value = JSON.stringify(value);
} catch (e) {
// Sometimes we can't stringify due to circular refs
// in complex objects, so we won't bother storing then.
return;
}
}
try {
setItem(key, value);
} catch (e) {
if (e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
// If we exceeded the quota, then we will sort
// by the expire time, and then remove the N oldest
var storedKeys = [];
var storedKey;
for (var i = 0; i < localStorage.length; i++) {
storedKey = localStorage.key(i);
if (storedKey.indexOf(CACHE_PREFIX + cacheBucket) === 0 && storedKey.indexOf(CACHE_SUFFIX) < 0) {
var mainKey = storedKey.substr((CACHE_PREFIX + cacheBucket).length);
var exprKey = expirationKey(mainKey);
var expiration = getItem(exprKey);
if (expiration) {
expiration = parseInt(expiration, EXPIRY_RADIX);
} else {
// TODO: Store date added for non-expiring items for smarter removal
expiration = MAX_DATE;
}
storedKeys.push({
key: mainKey,
size: (getItem(mainKey)||'').length,
expiration: expiration
});
}
}
// Sorts the keys with oldest expiration time last
storedKeys.sort(function(a, b) { return (b.expiration-a.expiration); });
var targetSize = (value||'').length;
while (storedKeys.length && targetSize > 0) {
storedKey = storedKeys.pop();
removeItem(storedKey.key);
removeItem(expirationKey(storedKey.key));
targetSize -= storedKey.size;
}
try {
setItem(key, value);
} catch (e) {
// value may be larger than total quota
return;
}
} else {
// If it was some other error, just give up.
return;
}
}
// If a time is specified, store expiration info in localStorage
if (time) {
setItem(expirationKey(key), (currentTime() + time).toString(EXPIRY_RADIX));
} else {
// In case they previously set a time, remove that info from localStorage.
removeItem(expirationKey(key));
}
},
/**
* Retrieves specified value from localStorage, if not expired.
* @param {string} key
* @return {string|Object}
*/
get: function(key) {
if (!supportsStorage()) return null;
// Return the de-serialized item if not expired
var exprKey = expirationKey(key);
var expr = getItem(exprKey);
if (expr) {
var expirationTime = parseInt(expr, EXPIRY_RADIX);
// Check if we should actually kick item out of storage
if (currentTime() >= expirationTime) {
removeItem(key);
removeItem(exprKey);
return null;
}
}
// Tries to de-serialize stored value if its an object, and returns the normal value otherwise.
var value = getItem(key);
if (!value || !supportsJSON()) {
return value;
}
try {
// We can't tell if its JSON or a string, so we try to parse
return JSON.parse(value);
} catch (e) {
// If we can't parse, it's probably because it isn't an object
return value;
}
},
/**
* Removes a value from localStorage.
* Equivalent to 'delete' in memcache, but that's a keyword in JS.
* @param {string} key
*/
remove: function(key) {
if (!supportsStorage()) return null;
removeItem(key);
removeItem(expirationKey(key));
},
/**
* Returns whether local storage is supported.
* Currently exposed for testing purposes.
* @return {boolean}
*/
supported: function() {
return supportsStorage();
},
/**
* Flushes all lscache items and expiry markers without affecting rest of localStorage
*/
flush: function() {
if (!supportsStorage()) return;
// Loop in reverse as removing items will change indices of tail
for (var i = localStorage.length-1; i >= 0 ; --i) {
var key = localStorage.key(i);
if (key.indexOf(CACHE_PREFIX + cacheBucket) === 0) {
localStorage.removeItem(key);
}
}
},
/**
* Appends CACHE_PREFIX so lscache will partition data in to different buckets.
* @param {string} bucket
*/
setBucket: function(bucket) {
cacheBucket = bucket+'-';
},
/**
* Get actual CACHE_PREFIX
* @return {string} bucket
*/
getBucket: function() {
return cacheBucket;
},
/**
* Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior.
*/
resetBucket: function() {
cacheBucket = '';
}
};
}();
| KKoPV/PVLng | public/js/lscache.js | JavaScript | mit | 8,561 |
var Rollout = require('..');
var assert = require('assert');
var Promise = require('bluebird');
var Group = Rollout.Group;
var User = Rollout.User;
describe('rollout', function() {
describe('constructor', function() {
it('should return a function', function() {
assert.equal('function', typeof Rollout);
});
it('should return a .create function', function() {
assert.equal('function', typeof Rollout.create);
});
it('should default to a local Redis instance when one isn\'t provided', function() {
assert.doesNotThrow(function() {
var rollout = new Rollout();
}, "Expected Rollout() to default to a local Redis instance.");
});
it('should create a new Rollout instance w/ .create()', function() {
assert(Rollout.create() instanceof Rollout);
});
it('should have a default user id of "id"', function() {
assert.equal(Rollout.create()._id, 'id');
});
it('should define a custom id', function() {
var rollout = Rollout.create();
rollout.id('foo');
assert.equal(rollout._id, 'foo');
});
it('should return a chainable interface (.id())', function() {
var rollout = Rollout.create();
assert(rollout.id() instanceof Rollout);
});
});
describe('.active()', function() {
it('should have an .active() method', function() {
assert.equal('function', typeof Rollout.create().active);
});
it('should throw an error when calling .active() without any arguments', function() {
var rollout = Rollout.create();
assert.throws(function() {
rollout.active();
}, Error);
});
it('should return a new promise when calling .active()', function() {
var rollout = Rollout.create();
assert(rollout.active('foo') instanceof Promise);
});
it.skip('should return "disabled" when a feature hasn\'t been set', function(done) {
var rollout = Rollout.create();
rollout.active('foobar').then(function(result) {
assert.equal(result, false);
done();
});
});
});
describe('groups', function() {
it('should define a .group() method', function() {
var rollout = Rollout.create();
assert.equal('function', typeof rollout.group);
});
it('should not throw when calling .group() with two params', function() {
var rollout = Rollout.create();
assert.doesNotThrow(function() {
rollout.group('all', function() {});
});
});
it('should throw an error when the second param to .group() isn\'t a function', function() {
var rollout = Rollout.create();
assert.throws(function() {
rollout.group('all', 123);
}, Error);
});
it('should add a member to the rollout:groups set', function(done) {
var rollout = Rollout.create();
var group = rollout.group('foobar', function(user) {
return true;
});
setTimeout(function() {
rollout.client.sismember(rollout.name('rollout:groups'), 'foobar', function(err, result) {
if (err) {
return done(err);
}
if (result == '1') {
done();
} else {
done(err);
}
});
}, 10);
});
it('should add a default group of all', function(done) {
var rollout = Rollout.create();
setTimeout(function() {
rollout.client.sismember('rollout:groups', 'all', function(err, result) {
if (err) {
return done(err);
}
if (result == '1') {
done();
} else {
done(err);
}
});
}, 10);
});
});
describe('user', function() {
var rollout = Rollout.create();
it('should define a fn', function() {
assert.equal('function', typeof rollout.user);
});
it('should return an instance', function() {
assert(rollout.user({ id: 1 }) instanceof User);
});
});
describe('deactivate', function() {
var rollout = Rollout.create();
it('should define a fn', function() {
assert.equal('function', typeof rollout.deactivate);
});
it('should return a Promise', function() {
assert(rollout.deactivate('foo') instanceof Promise);
});
});
describe('group', function() {
var rollout = Rollout.create();
it('should define a fn', function() {
assert.equal('function', typeof rollout.group);
});
});
describe('namespace', function() {
it('should define a .namespace() method', function() {
var rollout = Rollout.create();
assert.equal('function', typeof rollout.namespace);
});
it('should throw an error without any arguments', function() {
var rollout = Rollout.create();
assert.throws(function() {
rollout.namespace();
}, Error);
});
it('should throw an error with too many arguments', function() {
var rollout = Rollout.create();
assert.throws(function() {
rollout.namespace(1,2,3);
});
});
it('should throw if single param isn\'t a string', function() {
var rollout = Rollout.create();
assert.throws(function() {
rollout.namespace(1);
});
});
it('should be a chainable method', function() {
var rollout = Rollout.create();
assert(rollout.namespace('foobar') instanceof Rollout);
});
it('should define the default "all" group with a namespace', function(done) {
var rollout = Rollout.create().namespace('foobar');
setTimeout(function() {
rollout.client.sismember('foobar:rollout:groups', 'all', function(err, result) {
if (err) {
return done(err);
}
if (result == '1') {
done();
} else {
return done(err);
}
});
}, 30);
});
});
describe('.name()', function() {
it('should define a .name() method', function() {
var rollout = Rollout.create();
assert.equal('function', typeof rollout.name);
});
it('should throw an error if the key isn\'t defined', function() {
var rollout = Rollout.create();
assert.throws(function() {
rollout.name();
}, Error);
});
it('should return a string', function() {
var rollout = Rollout.create();
assert.equal('string', typeof rollout.name('foo'));
});
it('should return the name with a prepended namespace', function() {
var rollout = Rollout.create().namespace('faf');
assert.equal(rollout.name('heh'), 'faf:heh');
});
});
}); | thehydroimpulse/rollout | test/index.js | JavaScript | mit | 6,629 |
"use strict";
exports.__esModule = true;
exports.Func /*tion*/ = Func;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _lodashLangIsNumber = require("lodash/lang/isNumber");
var _lodashLangIsNumber2 = _interopRequireDefault(_lodashLangIsNumber);
var _util = require("../../../util");
var util = _interopRequireWildcard(_util);
var _types = require("../../../types");
var t = _interopRequireWildcard(_types);
var memberExpressionOptimisationVisitor = {
enter: function enter(node, parent, scope, state) {
var _this = this;
// check if this scope has a local binding that will shadow the rest parameter
if (this.isScope() && !scope.bindingIdentifierEquals(state.name, state.outerBinding)) {
return this.skip();
}
var stop = function stop() {
state.canOptimise = false;
_this.stop();
};
if (this.isArrowFunctionExpression()) return stop();
// skip over functions as whatever `arguments` we reference inside will refer
// to the wrong function
if (this.isFunctionDeclaration() || this.isFunctionExpression()) {
state.noOptimise = true;
this.traverse(memberExpressionOptimisationVisitor, state);
state.noOptimise = false;
return this.skip();
}
// is this a referenced identifier and is it referencing the rest parameter?
if (!this.isReferencedIdentifier({ name: state.name })) return;
if (!state.noOptimise && t.isMemberExpression(parent) && parent.computed) {
// if we know that this member expression is referencing a number then we can safely
// optimise it
var prop = parent.property;
if ((0, _lodashLangIsNumber2["default"])(prop.value) || t.isUnaryExpression(prop) || t.isBinaryExpression(prop)) {
state.candidates.push(this);
return;
}
}
stop();
}
};
function optimizeMemberExpression(parent, offset) {
var newExpr;
var prop = parent.property;
if (t.isLiteral(prop)) {
prop.value += offset;
prop.raw = String(prop.value);
} else {
// // UnaryExpression, BinaryExpression
newExpr = t.binaryExpression("+", prop, t.literal(offset));
parent.property = newExpr;
}
}
var hasRest = function hasRest(node) {
return t.isRestElement(node.params[node.params.length - 1]);
};
function Func(node, parent, scope, file) {
if (!hasRest(node)) return;
var restParam = node.params.pop();
var rest = restParam.argument;
var argsId = t.identifier("arguments");
// otherwise `arguments` will be remapped in arrow functions
argsId._shadowedFunctionLiteral = true;
// support patterns
if (t.isPattern(rest)) {
var pattern = rest;
rest = scope.generateUidIdentifier("ref");
var declar = t.variableDeclaration("let", pattern.elements.map(function (elem, index) {
var accessExpr = t.memberExpression(rest, t.literal(index), true);
return t.variableDeclarator(elem, accessExpr);
}));
node.body.body.unshift(declar);
}
// check if rest is used in member expressions and optimise for those cases
var state = {
outerBinding: scope.getBindingIdentifier(rest.name),
canOptimise: true,
candidates: [],
method: node,
name: rest.name
};
this.traverse(memberExpressionOptimisationVisitor, state);
// we only have shorthands and there's no other references
if (state.canOptimise && state.candidates.length) {
var _arr = state.candidates;
for (var _i = 0; _i < _arr.length; _i++) {
var candidate = _arr[_i];
candidate.replaceWith(argsId);
optimizeMemberExpression(candidate.parent, node.params.length);
}
return;
}
//
var start = t.literal(node.params.length);
var key = scope.generateUidIdentifier("key");
var len = scope.generateUidIdentifier("len");
var arrKey = key;
var arrLen = len;
if (node.params.length) {
// this method has additional params, so we need to subtract
// the index of the current argument position from the
// position in the array that we want to populate
arrKey = t.binaryExpression("-", key, start);
// we need to work out the size of the array that we're
// going to store all the rest parameters
//
// we need to add a check to avoid constructing the array
// with <0 if there are less arguments than params as it'll
// cause an error
arrLen = t.conditionalExpression(t.binaryExpression(">", len, start), t.binaryExpression("-", len, start), t.literal(0));
}
var loop = util.template("rest", {
ARRAY_TYPE: restParam.typeAnnotation,
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key,
LEN: len
});
loop._blockHoist = node.params.length + 1;
node.body.body.unshift(loop);
} | astoimenov/ln-blog | node_modules/laravel-elixir/node_modules/gulp-babel/node_modules/babel-core/lib/babel/transformation/transformers/es6/parameters.rest.js | JavaScript | mit | 5,076 |
/**
* Joe Zim's jQuery URL Parser Plugin (JZ Parse URL) 1.0
*
* Copyright (c) 2012 Joseph Zimmerman http://www.joezimjs.com
* License: http://www.opensource.org/licenses/gpl-3.0.html
*/
var JZ=JZ||{},jQuery=jQuery||null;
(function($,window,undefined){var document=window.document;var createLink=function(url){var link;if(url&&typeof url==="string"){var div=document.createElement("div");div.innerHTML="<a></a>";div.firstChild.href=url;div.innerHTML=div.innerHTML;link=div.firstChild}else link=window.location;return link};var normalizePath=function(path){if(path.substring(0,1)!=="/")path="/"+path;return path};var parseQueryString=function(query){var params={},i,l;if(!query.length)return params;query=query.substring(1);query=
query.split("&");for(i=0,l=query.length;i<l;i++){var split=query[i].split("=");split[1]=split[1]===undefined?true:split[1];params[unescape(split[0])]=unescape(split[1])}return params};var Parser=function(link){this.hash=link.hash;this.host=link.host;this.hostname=link.hostname;this.href=link.href;this.path=normalizePath(link.pathname);this.pathname=this.path;this.port=link.port;this.protocol=link.protocol;this.query=parseQueryString(link.search);this.search=link.search;this.url=link.href;this.get=
function(param){return this.query[param]}};$.parseUrl=function(url){var link=createLink(url);return new Parser(link)}})(jQuery||JZ,window); | studiomohawk/Seven | script/jquery.parseurl.min.js | JavaScript | mit | 1,385 |
/*global define*/
define(['jquery', 'underscore', 'oro/translator', 'oro/mediator', 'oro/modal', 'oro/datagrid/abstract-listener'],
function($, _, __, mediator, Modal, AbstractListener) {
'use strict';
/**
* Listener for entity edit form and datagrid
*
* @export oro/datagrid/column-form-listener
* @class oro.datagrid.ColumnFormListener
* @extends oro.datagrid.AbstractListener
*/
var ColumnFormListener = AbstractListener.extend({
/** @param {Object} */
selectors: {
included: null,
excluded: null
},
/**
* Initialize listener object
*
* @param {Object} options
*/
initialize: function (options) {
if (!_.has(options, 'selectors')) {
throw new Error('Field selectors is not specified');
}
this.selectors = options.selectors;
AbstractListener.prototype.initialize.apply(this, arguments);
},
/**
* Set datagrid instance
*/
setDatagridAndSubscribe: function () {
AbstractListener.prototype.setDatagridAndSubscribe.apply(this, arguments);
this.$gridContainer.on('preExecute:refresh:' + this.gridName, this._onExecuteRefreshAction.bind(this));
this.$gridContainer.on('preExecute:reset:' + this.gridName, this._onExecuteResetAction.bind(this));
this._clearState();
this._restoreState();
/**
* Restore include/exclude state from pagestate
*/
mediator.bind("pagestate_restored", function () {
this._restoreState();
}, this);
},
/**
* Fills inputs referenced by selectors with ids need to be included and to excluded
*
* @param {*} id model id
* @param {Backbone.Model} model
* @protected
*/
_processValue: function(id, model) {
var original = this.get('original');
var included = this.get('included');
var excluded = this.get('excluded');
var isActive = model.get(this.columnName);
var originallyActive;
if (_.has(original, id)) {
originallyActive = original[id];
} else {
originallyActive = !isActive;
original[id] = originallyActive;
}
if (isActive) {
if (originallyActive) {
included = _.without(included, [id]);
} else {
included = _.union(included, [id]);
}
excluded = _.without(excluded, id);
} else {
included = _.without(included, id);
if (!originallyActive) {
excluded = _.without(excluded, [id]);
} else {
excluded = _.union(excluded, [id]);
}
}
this.set('included', included);
this.set('excluded', excluded);
this.set('original', original);
this._synchronizeState();
},
/**
* Clears state of include and exclude properties to empty values
*
* @private
*/
_clearState: function () {
this.set('included', []);
this.set('excluded', []);
this.set('original', {});
},
/**
* Synchronize values of include and exclude properties with form fields and datagrid parameters
*
* @private
*/
_synchronizeState: function () {
var included = this.get('included');
var excluded = this.get('excluded');
if (this.selectors.included) {
$(this.selectors.included).val(included.join(','));
}
if (this.selectors.excluded) {
$(this.selectors.excluded).val(excluded.join(','));
}
mediator.trigger('datagrid:setParam:' + this.gridName, 'data_in', included);
mediator.trigger('datagrid:setParam:' + this.gridName, 'data_not_in', excluded);
},
/**
* Explode string into int array
*
* @param string
* @return {Array}
* @private
*/
_explode: function(string) {
if (!string) {
return [];
}
return _.map(string.split(','), function(val) {return val ? parseInt(val, 10) : null});
},
/**
* Restore values of include and exclude properties
*
* @private
*/
_restoreState: function () {
var included = '';
var excluded = '';
if (this.selectors.included && $(this.selectors.included).length) {
included = this._explode($(this.selectors.included).val());
this.set('included', included);
}
if (this.selectors.excluded && $(this.selectors.excluded).length) {
excluded = this._explode($(this.selectors.excluded).val());
this.set('excluded', excluded)
}
if (included || excluded) {
mediator.trigger('datagrid:setParam:' + this.gridName, 'data_in', included);
mediator.trigger('datagrid:setParam:' + this.gridName, 'data_not_in', excluded);
mediator.trigger('datagrid:restoreState:' + this.gridName, this.columnName, this.dataField, included, excluded);
}
},
/**
* Confirms refresh action that before it will be executed
*
* @param {oro.datagrid.AbstractAction} action
* @param {Object} options
* @private
*/
_onExecuteRefreshAction: function (e, action, options) {
this._confirmAction(action, options, 'refresh', {
title: __('Refresh Confirmation'),
content: __('Your local changes will be lost. Are you sure you want to refresh grid?')
});
},
/**
* Confirms reset action that before it will be executed
*
* @param {oro.datagrid.AbstractAction} action
* @param {Object} options
* @private
*/
_onExecuteResetAction: function(e, action, options) {
this._confirmAction(action, options, 'reset', {
title: __('Reset Confirmation'),
content: __('Your local changes will be lost. Are you sure you want to reset grid?')
});
},
/**
* Asks user a confirmation if there are local changes, if user confirms then clears state and runs action
*
* @param {oro.datagrid.AbstractAction} action
* @param {Object} actionOptions
* @param {String} type "reset" or "refresh"
* @param {Object} confirmModalOptions Options for confirm dialog
* @private
*/
_confirmAction: function(action, actionOptions, type, confirmModalOptions) {
this.confirmed = this.confirmed || {};
if (!this.confirmed[type] && this._hasChanges()) {
actionOptions.doExecute = false; // do not execute action until it's confirmed
this._openConfirmDialog(type, confirmModalOptions, function () {
// If confirmed, clear state and run action
this.confirmed[type] = true;
this._clearState();
this._synchronizeState();
action.run();
});
}
this.confirmed[type] = false;
},
/**
* Returns TRUE if listener contains user changes
*
* @return {Boolean}
* @private
*/
_hasChanges: function() {
return !_.isEmpty(this.get('included')) || !_.isEmpty(this.get('excluded'));
},
/**
* Opens confirm modal dialog
*/
_openConfirmDialog: function(type, options, callback) {
this.confirmModal = this.confirmModal || {};
if (!this.confirmModal[type]) {
this.confirmModal[type] = new Modal(_.extend({
title: __('Confirmation'),
okText: __('Ok, got it.'),
className: 'modal modal-primary',
okButtonClass: 'btn-primary btn-large'
}, options));
this.confirmModal[type].on('ok', _.bind(callback, this));
}
this.confirmModal[type].open();
}
});
ColumnFormListener.init = function ($gridContainer, gridName) {
var metadata = $gridContainer.data('metadata');
var options = metadata.options || {};
if (options.columnListener) {
new ColumnFormListener(_.extend({ $gridContainer: $gridContainer, gridName: gridName }, options.columnListener));
}
};
return ColumnFormListener;
});
| minhnguyen-balance/oro_platform | web/bundles/orodatagrid/js/datagrid/listener/column-form-listener.js | JavaScript | mit | 9,099 |
version https://git-lfs.github.com/spec/v1
oid sha256:b42e0d4e32e5c3b9240210f64c7ea0f82df3d7b2dd1d81b5696807487fe47b25
size 4157
| yogeshsaroya/new-cdnjs | ajax/libs/codemirror/4.1.0/mode/sieve/sieve.js | JavaScript | mit | 129 |
import { Component } from '../component.js';
import { ComponentSystem } from '../system.js';
import { AnimationComponent } from './component.js';
import { AnimationComponentData } from './data.js';
var _schema = [
'enabled',
'assets',
'speed',
'loop',
'activate',
'animations',
'skeleton',
'model',
'prevAnim',
'currAnim',
'fromSkel',
'toSkel',
'blending',
'blendTimeRemaining',
'playing'
];
/**
* @class
* @name pc.AnimationComponentSystem
* @augments pc.ComponentSystem
* @classdesc The AnimationComponentSystem manages creating and deleting AnimationComponents.
* @description Create an AnimationComponentSystem.
* @param {pc.Application} app - The application managing this system.
*/
function AnimationComponentSystem(app) {
ComponentSystem.call(this, app);
this.id = 'animation';
this.ComponentType = AnimationComponent;
this.DataType = AnimationComponentData;
this.schema = _schema;
this.on('beforeremove', this.onBeforeRemove, this);
this.on('update', this.onUpdate, this);
ComponentSystem.bind('update', this.onUpdate, this);
}
AnimationComponentSystem.prototype = Object.create(ComponentSystem.prototype);
AnimationComponentSystem.prototype.constructor = AnimationComponentSystem;
Component._buildAccessors(AnimationComponent.prototype, _schema);
Object.assign(AnimationComponentSystem.prototype, {
initializeComponentData: function (component, data, properties) {
properties = ['activate', 'enabled', 'loop', 'speed', 'assets'];
ComponentSystem.prototype.initializeComponentData.call(this, component, data, properties);
},
cloneComponent: function (entity, clone) {
var key;
this.addComponent(clone, {});
clone.animation.assets = entity.animation.assets.slice();
clone.animation.data.speed = entity.animation.speed;
clone.animation.data.loop = entity.animation.loop;
clone.animation.data.activate = entity.animation.activate;
clone.animation.data.enabled = entity.animation.enabled;
var clonedAnimations = { };
var animations = entity.animation.animations;
for (key in animations) {
if (animations.hasOwnProperty(key)) {
clonedAnimations[key] = animations[key];
}
}
clone.animation.animations = clonedAnimations;
var clonedAnimationsIndex = { };
var animationsIndex = entity.animation.animationsIndex;
for (key in animationsIndex) {
if (animationsIndex.hasOwnProperty(key)) {
clonedAnimationsIndex[key] = animationsIndex[key];
}
}
clone.animation.animationsIndex = clonedAnimationsIndex;
},
onBeforeRemove: function (entity, component) {
component.onBeforeRemove();
},
onUpdate: function (dt) {
var components = this.store;
for (var id in components) {
if (components.hasOwnProperty(id)) {
var component = components[id];
var componentData = component.data;
if (componentData.enabled && component.entity.enabled) {
// update blending
if (componentData.blending) {
componentData.blend += dt * componentData.blendSpeed;
if (componentData.blend >= 1.0) {
componentData.blend = 1.0;
}
}
// update skeleton
if (componentData.playing) {
var skeleton = componentData.skeleton;
if (skeleton !== null && componentData.model !== null) {
if (componentData.blending) {
skeleton.blend(componentData.fromSkel, componentData.toSkel, componentData.blend);
} else {
// Advance the animation, interpolating keyframes at each animated node in
// skeleton
var delta = dt * componentData.speed;
skeleton.addTime(delta);
if (componentData.speed > 0 && (skeleton._time === skeleton._animation.duration) && !componentData.loop) {
componentData.playing = false;
} else if (componentData.speed < 0 && skeleton._time === 0 && !componentData.loop) {
componentData.playing = false;
}
}
if (componentData.blending && (componentData.blend === 1.0)) {
skeleton.animation = componentData.toSkel._animation;
}
skeleton.updateGraph();
}
}
// update anim controller
var animEvaluator = componentData.animEvaluator;
if (animEvaluator) {
// force all clip's speed and playing state from the component
for (var i = 0; i < animEvaluator.clips.length; ++i) {
var clip = animEvaluator.clips[i];
clip.speed = componentData.speed;
if (!componentData.playing) {
clip.pause();
} else {
clip.resume();
}
}
// update blend weight
if (componentData.blending) {
animEvaluator.clips[1].blendWeight = componentData.blend;
}
animEvaluator.update(dt);
}
// clear blending flag
if (componentData.blending && componentData.blend === 1.0) {
componentData.blending = false;
}
}
}
}
}
});
export { AnimationComponentSystem };
| aidinabedi/playcanvas-engine | src/framework/components/animation/system.js | JavaScript | mit | 6,273 |
const uninstall = () => {
delete global.requestAnimationFrame;
delete global.cancelAnimationFrame;
};
const install = () => {
if (typeof window === 'undefined') {
return;
}
let lastTime = 0;
const vendors = ['ms', 'moz', 'webkit', 'o'];
for (let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x] + 'CancelAnimationFrame'] ||
window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback) {
const currTime = new Date().getTime();
const timeToCall = Math.max(0, 16 - (currTime - lastTime));
const id = window.setTimeout(() => {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}
global.requestAnimationFrame =
global.requestAnimationFrame || window.requestAnimationFrame;
global.cancelAnimationFrame =
global.cancelAnimationFrame || window.cancelAnimationFrame;
};
export default { install, uninstall };
| wix/wix-style-react | packages/wix-style-react/testkit/polyfills/request-animation-frame.js | JavaScript | mit | 1,308 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.toolbar = 'ArticleToolbar';
config.toolbar_ArticleToolbar =
[
{ name:'document', items:[ 'Source', '-', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates' ] },
{ name:'clipboard', items:[ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
{ name:'editing', items:[ 'Find', 'Replace', '-', 'SelectAll', '-', 'SpellChecker', 'Scayt' ] },
{ name:'forms', items:[ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
'/',
{ name:'basicstyles', items:[ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
{ name:'paragraph', items:[ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] },
{ name:'links', items:[ 'Link', 'Unlink', 'Anchor' ] },
{ name:'insert', items:[ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak' ] },
'/',
{ name:'styles', items:[ 'Styles', 'Format', 'Font', 'FontSize' ] },
{ name:'colors', items:[ 'TextColor', 'BGColor' ] },
{ name:'tools', items:[ 'Maximize', 'ShowBlocks', '-', 'About' ] }
];
};
| saggiyogesh/nodeportal | public/editor/ckeditor/config.js | JavaScript | mit | 1,772 |
import { TempNode } from './TempNode.js';
var declarationRegexp = /^([a-z_0-9]+)\s([a-z_0-9]+)\s?\=?\s?(.*?)(\;|$)/i;
function ConstNode( src, useDefine ) {
TempNode.call( this );
this.parse( src || ConstNode.PI, useDefine );
}
ConstNode.PI = 'PI';
ConstNode.PI2 = 'PI2';
ConstNode.RECIPROCAL_PI = 'RECIPROCAL_PI';
ConstNode.RECIPROCAL_PI2 = 'RECIPROCAL_PI2';
ConstNode.LOG2 = 'LOG2';
ConstNode.EPSILON = 'EPSILON';
ConstNode.prototype = Object.create( TempNode.prototype );
ConstNode.prototype.constructor = ConstNode;
ConstNode.prototype.nodeType = 'Const';
ConstNode.prototype.getType = function ( builder ) {
return builder.getTypeByFormat( this.type );
};
ConstNode.prototype.parse = function ( src, useDefine ) {
this.src = src || '';
var name, type, value = '';
var match = this.src.match( declarationRegexp );
this.useDefine = useDefine || this.src.charAt( 0 ) === '#';
if ( match && match.length > 1 ) {
type = match[ 1 ];
name = match[ 2 ];
value = match[ 3 ];
} else {
name = this.src;
type = 'f';
}
this.name = name;
this.type = type;
this.value = value;
};
ConstNode.prototype.build = function ( builder, output ) {
if ( output === 'source' ) {
if ( this.value ) {
if ( this.useDefine ) {
return '#define ' + this.name + ' ' + this.value;
}
return 'const ' + this.type + ' ' + this.name + ' = ' + this.value + ';';
} else if ( this.useDefine ) {
return this.src;
}
} else {
builder.include( this );
return builder.format( this.name, this.getType( builder ), output );
}
};
ConstNode.prototype.generate = function ( builder, output ) {
return builder.format( this.name, this.getType( builder ), output );
};
ConstNode.prototype.copy = function ( source ) {
TempNode.prototype.copy.call( this, source );
this.parse( source.src, source.useDefine );
return this;
};
ConstNode.prototype.toJSON = function ( meta ) {
var data = this.getJSONNode( meta );
if ( ! data ) {
data = this.createJSONNode( meta );
data.src = this.src;
if ( data.useDefine === true ) data.useDefine = true;
}
return data;
};
export { ConstNode };
| 06wj/three.js | examples/jsm/nodes/core/ConstNode.js | JavaScript | mit | 2,149 |
(function(){
var width = 1500,
height = 1500,
root;
var force = d3.layout.force()
.linkDistance(80)
.charge(-300)
.gravity(.05)
.size([width, height])
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
queue()
.defer(d3.json, "../../sample_data/test.json")
.defer(d3.json, "../../sample_data/viz.json")
.await(function(error, file1, file2) { console.log(file1, file2); });
d3.json("../../sample_data/test.json", function(error, json) {
if (error) throw error;
console.log(json);
// linkScale = d3.scale.linear()
// .domain([])
// .range([]);
root = json;
update();
});
function update() {
var nodes = flatten(root),
links = d3.layout.tree().links(nodes);
// Restart the force layout.
force
.nodes(nodes)
.links(links)
.start();
// Update links.
link = link.data(links, function(d) { return d.target.id; });
link.exit().remove();
link.enter().insert("line", ".node")
// .attr("class", "link")
.attr("stroke-width", function(d){
console.log('Source: ', d.source); // Sources are the repositories/branches.
console.log('Target: ', d.target); // Targets are the contributors.
if(d.source.key){
return Math.sqrt(d.source.values);
}
else if(d.target.key){
return Math.sqrt(d.target.values);
}
else{
return 2;
}
})
.attr("stroke", function(d){
return (d.source.key || d.target.key) ? '#88D3A1' : '#646464';
});
// Update nodes.
node = node.data(nodes, function(d) { console.log('Node: ', d); return d.id; });
node.exit().remove();
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.on("click", click)
.call(force.drag);
nodeEnter.append("circle")
.attr("r", function(d, i) {
return (d.values) ? d.values : 4.5;
});
nodeEnter.append("text")
.attr("dy", ".35em")
.text(function(d) { return (d.name) ? d.name : d.key; })
.style("fill", "white");
node.select("circle")
.style("fill", function(d) {
return "#805489";
});
}
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
// Toggle children on click.
function click(d) {
if (d3.event.defaultPrevented) return; // ignore drag
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update();
}
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children)
node.children.forEach(recurse);
if (!node.id)
node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
})(); | KenChan23/git-collaboration-visualization | public/js/visualization.js | JavaScript | mit | 3,439 |
/**
* Justin Shih
* http://justinshih.com
*
* @filename core.js
* @author Justin Shih
* @pages All pages
*
*/
var Core = (function ($) {
"use strict";
// private alias to settings
var s;
return {
settings: function() {
this.logo = $(".mainlogo");
this.category = $("a.category");
this.aboutTextWrapper = ".column-about-text";
this.aboutTextItem = ".text-item";
this.aboutActive = "about-active";
this.productItem = $("a.product");
this.flipped = "flipped";
},
init: function() {
s = new this.settings();
this.loadContent();
this.bindUIAction();
this.productHover();
},
loadContent: function(){
$(document).on("click", "a.category", function (event){
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
success: function(data) {
$("#indexrow").hide().html($(data).find(".row").children()).fadeIn("slow");
$(".product-fullsize").featherlight();
}
})
return false; //for good measure
});
window.onpopstate = function() {
$('#indexrow').hide().html(location.href).find(".row").fadeIn("slow");
};
},
bindUIAction: function() {
$(document).on("click", ".expandItem", function (e) {
var _this = $(this);
if(!_this.next(s.aboutTextWrapper).hasClass(s.aboutActive)){
$(this).next(s.aboutTextWrapper).addClass(s.aboutActive);
}
});
$(document).on("click", ".js-about-close", function (e) {
var _this = $(this);
if(_this.parent(s.aboutTextWrapper).hasClass(s.aboutActive)){
_this.parent(s.aboutTextWrapper).removeClass(s.aboutActive);
}
});
$(document).on("click", ".js-product-trigger", function (e){
var _this = $(this);
e.preventDefault();
if(!_this.hasClass("active")){
_this.addClass("active").siblings().removeClass('active');
$(".product-item").each(function (e) {
$(this).toggleClass(s.flipped);
});
}
});
},
hoverItemOver: function(el) {
if(!el.attr('data-src')) {
el.attr('data-src', el.attr('src'));
}
// change to hover image
el.attr("src", el.attr('data-hover'));
},
hoverItemOut: function (el) {
// change back to original image
el.attr('src', el.attr('data-src'));
},
productHover: function(){
// product rollover image on hover
$(document).on({
mouseenter: function() {
if(!$(".product-item").hasClass("flipped")){
Core.hoverItemOver($(this).find("img.front[data-hover]:visible"));
$(this).find("img.front[data-hover]:visible").next().addClass("active");
} else {
Core.hoverItemOver($(this).find("img.back[data-hover]:visible"));
$(this).find("img.back[data-hover]:visible").next().addClass("active");
}
},
mouseleave: function() {
if(!$(".product-item").hasClass("flipped")){
Core.hoverItemOut($(this).find("img.front[data-hover]:visible"));
$(this).find("img.front[data-hover]:visible").next().removeClass("active");
} else {
Core.hoverItemOut($(this).find("img.back[data-hover]:visible"));
$(this).find("img.back[data-hover]:visible").next().removeClass("active");
}
}
}, ".product-item");
}
};
})(jQuery);
jQuery(document).ready(function($) {
Core.init();
}); | timothydouglas/justinshihportfolio | skin/js/core.js | JavaScript | mit | 4,218 |