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
|
---|---|---|---|---|---|
'use strict';
angular.module('exiaSecuDemoWebApp')
.service('CustomerService', function ($log, $q, Restangular) {
var customers = Restangular.all('customer');
this.fetchAll = function () {
return customers.getList();
};
this.save = function (customer) {
return customer.save();
};
this.delete = function (customer) {
return customer.remove();
};
this.get = function (id) {
return customers.get(id);
};
});
|
cyrilchapon/exia-secu-demo-web
|
app/scripts/services/customer.js
|
JavaScript
|
mit
| 476 |
function $9x19MM(type, rounds) {
if(type == undefined) type = Ammo.TYPE_BALL;
if(rounds == undefined) rounds = 15;
Ammo.call(this, Ammo.$9x19MM, {
name: '9x19mm',
weight: 0.1,
size: Item.SMALL,
type: type,
rounds: rounds
});
}
$9x19MM.prototype = new Ammo();
$9x19MM.constructor = $9x19MM;
|
misantronic/RPG
|
js/items/ammo/9mm.js
|
JavaScript
|
mit
| 306 |
Package.describe({
name: "nova:categories",
summary: "Telescope tags package",
version: "1.0.0",
git: "https://github.com/TelescopeJS/telescope-tags.git"
});
Package.onUse(function (api) {
api.versionsFrom("METEOR@1.0");
api.use([
'nova:core@1.0.0',
'nova:posts@1.0.0',
'nova:users@1.0.0'
]);
api.mainModule("lib/server.js", "server");
api.mainModule("lib/client.js", "client");
});
|
JstnEdr/Telescope
|
packages/nova-categories/package.js
|
JavaScript
|
mit
| 417 |
var config = require('./config');
var database = require('./db');
var Queue = require('./lib/Queue');
var queue = new Queue( config );
var processors = {
'test': function( data , jobIsDone ) {
console.log('#winning' , data );
jobIsDone();
}
};
var worker = new queue.Worker( config.database.name );
worker.register( processors );
worker.on('dequeued', function (data) {
console.log('worker dequeued job %s', data._id );
});
worker.on('failed', function (data) {
console.log('job %s failed', data._id , data.data );
});
worker.on('complete', function (data) {
console.log('job %s complete', data._id );
});
worker.on('error', function (err) {
console.log('worker error', err );
});
worker.start();
|
martindale/maki
|
worker.js
|
JavaScript
|
mit
| 723 |
'use strict'
const snakeCase = require('snake-case')
module.exports = (config, name) => {
const omit = (object, keys) => (
Object.keys(object).reduce((i, key) => {
if (keys.indexOf(key) === -1) {
i[key] = object[key]
}
return i
}, {})
)
const reduce = (object, prefix) => {
const toEnv = (index, prop) => {
let key = prop
if (name && !prefix) {
key = name + '_' + key
} else if (prefix && !name) {
key = prefix + '_' + key
} else if (prefix) {
key = prefix + '__' + key
}
if (!name) {
key = snakeCase(key).toUpperCase()
}
const value = object[prop]
if (typeof value === 'object') {
const reduced = reduce(value, key)
return Object.assign(index, reduced)
}
index[key] = value
return index
}
return Object.keys(object).reduce(toEnv, {})
}
const omits = [
'_',
'config',
'configs'
]
const omitted = omit(config, omits)
return reduce(omitted)
}
|
tlvince/rc2env
|
index.js
|
JavaScript
|
mit
| 1,043 |
const ElOption = require('../select/src/option');
ElOption.install = function(Vue) {
Vue.component(ElOption.name, ElOption);
};
module.exports = ElOption;
|
slovebj/zxui
|
packages/option/index.js
|
JavaScript
|
mit
| 159 |
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.2): tab.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tab = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tab';
var VERSION = '4.0.0-alpha';
var DATA_KEY = 'bs.tab';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active',
FADE: 'fade',
IN: 'in'
};
var Selector = {
A: 'a',
LI: 'li',
DROPDOWN: '.dropdown',
UL: 'ul:not(.dropdown-menu)',
FADE_CHILD: '> .nav-item .fade, > .fade',
ACTIVE: '.active',
ACTIVE_CHILD: '> .nav-item > .active, > .active',
DATA_TOGGLE: '[data-toggle="tab"], [data-toggle="pill"]',
DROPDOWN_TOGGLE: '.dropdown-toggle',
DROPDOWN_ACTIVE_CHILD: '> .dropdown-menu .active'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Tab = (function () {
function Tab(element) {
_classCallCheck(this, Tab);
this._element = element;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Tab, [{
key: 'show',
// public
value: function show() {
var _this = this;
if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.ACTIVE)) {
return;
}
var target = undefined;
var previous = undefined;
var ulElement = $(this._element).closest(Selector.UL)[0];
var selector = Util.getSelectorFromElement(this._element);
if (ulElement) {
previous = $.makeArray($(ulElement).find(Selector.ACTIVE));
previous = previous[previous.length - 1];
}
var hideEvent = $.Event(Event.HIDE, {
relatedTarget: this._element
});
var showEvent = $.Event(Event.SHOW, {
relatedTarget: previous
});
if (previous) {
$(previous).trigger(hideEvent);
}
$(this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
return;
}
if (selector) {
target = $(selector)[0];
}
this._activate(this._element, ulElement);
var complete = function complete() {
var hiddenEvent = $.Event(Event.HIDDEN, {
relatedTarget: _this._element
});
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: previous
});
$(previous).trigger(hiddenEvent);
$(_this._element).trigger(shownEvent);
};
if (target) {
this._activate(target, target.parentNode, complete);
} else {
complete();
}
}
}, {
key: 'dispose',
value: function dispose() {
$.removeClass(this._element, DATA_KEY);
this._element = null;
}
// private
}, {
key: '_activate',
value: function _activate(element, container, callback) {
var active = $(container).find(Selector.ACTIVE_CHILD)[0];
var isTransitioning = callback && Util.supportsTransitionEnd() && (active && $(active).hasClass(ClassName.FADE) || Boolean($(container).find(Selector.FADE_CHILD)[0]));
var complete = $.proxy(this._transitionComplete, this, element, active, isTransitioning, callback);
if (active && isTransitioning) {
$(active).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
if (active) {
$(active).removeClass(ClassName.IN);
}
}
}, {
key: '_transitionComplete',
value: function _transitionComplete(element, active, isTransitioning, callback) {
if (active) {
$(active).removeClass(ClassName.ACTIVE);
var dropdownChild = $(active).find(Selector.DROPDOWN_ACTIVE_CHILD)[0];
if (dropdownChild) {
$(dropdownChild).removeClass(ClassName.ACTIVE);
}
active.setAttribute('aria-expanded', false);
}
$(element).addClass(ClassName.ACTIVE);
element.setAttribute('aria-expanded', true);
if (isTransitioning) {
Util.reflow(element);
$(element).addClass(ClassName.IN);
} else {
$(element).removeClass(ClassName.FADE);
}
if (element.parentNode && $(element.parentNode).hasClass(ClassName.DROPDOWN_MENU)) {
var dropdownElement = $(element).closest(Selector.DROPDOWN)[0];
if (dropdownElement) {
$(dropdownElement).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
}
element.setAttribute('aria-expanded', true);
}
if (callback) {
callback();
}
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
if (!data) {
data = data = new Tab(this);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Tab;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
Tab._jQueryInterface.call($(this), 'show');
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Tab._jQueryInterface;
$.fn[NAME].Constructor = Tab;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tab._jQueryInterface;
};
return Tab;
})(jQuery);
|
adamrunner/designport-backup-server
|
javascripts/bootstrap/tab.js
|
JavaScript
|
mit
| 7,726 |
'use strict';
var LoadoutData = require('./LoadoutData.js');
var FactionData = require('./FactionData.js');
// API Object
// "Death":{
// "attacker_character_id":"",
// "attacker_fire_mode_id":"",
// "attacker_loadout_id":"",
// "attacker_vehicle_id":"",
// "attacker_weapon_id":"",
// "character_id":"",
// "character_loadout_id":"",
// "event_name":"Death",
// "is_critical":"",
// "is_headshot":"",
// "timestamp":"",
// "vehicle_id":"",
// "world_id":"",
// "zone_id":""
// }
var Death = function(attackerLoadoutId, loadoutId) {
this.attackerFaction = LoadoutData.getLoadout(attackerLoadoutId).faction;
this.faction = LoadoutData.getLoadout(loadoutId) .faction;
};
module.exports = Death;
|
jtheis85/BattleCompanion
|
_prototypes/Data/Death.js
|
JavaScript
|
mit
| 775 |
(function(window, document, $) {
"use strict";
var site = window.SITE,
viewName = "index.photography",
ui = {
el: "#photography",
backstretchEl: ".backstretch-wrap",
},
$backstretchEl = $(ui.el).find(ui.backstretchEl),
partialImagesPath = "images/photos/",
classNames = {
hideHeaders: "hide-headers",
fullScreenControl: "full-screen-control",
iconFullScreenBase: "icon-fullscreen-",
directionControl: "direction-control",
paused: "paused",
playing: "playing",
},
backstretchImages = [
// "http://farm8.staticflickr.com/7035/6464821765_36a618a812_o.jpg", /* Paris opera */
{
url: "stuck-in-traffic",
},
{
url: "hana",
},
{
url: "big-ben",
alignY: 0.7,
},
{
url: "cat",
alignY: 0,
},
{
url: "double-rainbow-in-paris",
},
{
url: "autumn-in-zrinjevac",
},
{
url: "paris-sunset",
},
{
url: "flowers",
},
{
url: "tower-bridge",
},
{
url: "adriatic-sea",
},
{
url: "dijana",
alignY: 1,
},
],
backstretchOptions = {
duration: 5000,
fade: 750,
preload: 1,
},
initBackstretch = function(){
if ($.fn.backstretch){
// init backstrect plugin
$backstretchEl.backstretch(prepareImages(backstretchImages), backstretchOptions);
// init events
initEvents();
}
else {
console.warn("Backstretch init failed");
}
},
initEvents = function(){
$(ui.el).on("click", function(e){
e.preventDefault();
var $el = $(this),
$target = $(e.target);
if ($target.is("."+classNames.fullScreenControl)) {
// running in the blind here, but there does not seem to be a reliable/trivial method
// to figure out the fullscreen state
var isEnabled = $target.hasClass(classNames.iconFullScreenBase+"on");
// trigger fullscreen or close it
site.views.run("common", "fullScreen" + (isEnabled ? "Request" : "Exit"), {element: this});
// trigger resize just in case
$backstretchEl.backstretch("resize");
// take care of the presentation
$target.toggleClass(classNames.iconFullScreenBase+"on", !isEnabled)
.toggleClass(classNames.iconFullScreenBase+"off", isEnabled);
window.setTimeout(function(){
$el.toggleClass(classNames.hideHeaders, isEnabled);
}, 3*1000);
}
else if ($target.is("."+classNames.directionControl)) {
cycleThroughSlides($target.attr("data-direction"));
}
else {
var isPaused = $el.hasClass(classNames.paused);
$el.toggleClass(classNames.paused, !isPaused)
.toggleClass(classNames.playing, isPaused);
$backstretchEl.backstretch(isPaused ? "resume" : "pause");
}
});
$(document).on("keydown", function(e){
switch (e.keyCode) {
case 37:
cycleThroughSlides("prev");
break;
case 39:
cycleThroughSlides("next");
break;
}
});
},
cycleThroughSlides = function(direction) {
var $el = $(ui.el);
$backstretchEl.backstretch(direction);
$el.removeClass("prev next");
$el[0].getClientRects(); // trigger layout
$el.addClass(direction);
},
prepareImages = function(imagesArr){
var fullImagesPath = site.settings.assetsUrl.local + partialImagesPath,
isWebPSupported = $("html").hasClass("webp");
imagesArr.forEach(function(el, i, arr){
el.url = fullImagesPath + el.url + "." + (isWebPSupported ? "webp" : "jpg");
});
return imagesArr;
},
exports = {
init: function(){
$(window).on("load."+viewName, function(){
initBackstretch();
});
},
classNames: classNames,
};
site.views.register(viewName, exports);
})(this, this.document, jQuery);
|
iamvanja/vanja.gavric.org
|
src/assets/js/site/views/view.index.photography.js
|
JavaScript
|
mit
| 5,105 |
const chai = require('chai');
const Card = require('../../../client/src/shared/card');
const expect = chai.expect;
describe('Card', () => {
it('Invalid suit', () => {
expect(() => new Card('invalid', 1)).to.throw('Invalid suit');
});
it('Invalid value (not a number)', () => {
expect(() => new Card(Card.Suits.SPADES, 'a')).to.throw('Invalid value');
});
it('Invalid value (number < 1)', () => {
expect(() => new Card(Card.Suits.SPADES, 0)).to.throw('Invalid value');
});
it('Invalid value (number > 13)', () => {
expect(() => new Card(Card.Suits.SPADES, 14)).to.throw('Invalid value');
});
it('Valid card (ace of spades)', () => {
let card = new Card(Card.Suits.SPADES, 1);
expect(card.suit).to.equal(Card.Suits.SPADES);
expect(card.value).to.equal(1);
});
it('Valid card (king of diamonds)', () => {
let card = new Card(Card.Suits.DIAMONDS, 13);
expect(card.suit).to.equal(Card.Suits.DIAMONDS);
expect(card.value).to.equal(13);
});
});
|
patteri/slave-cardgame
|
server/tests/common/card.test.js
|
JavaScript
|
mit
| 1,009 |
var searchData=
[
['n',['n',['../classOpenBabel_1_1OBRateData.shtml#a3a2d440e7729afe454180909de5cee32afe0cb765d0bfc2535a3f5b124ec8f887',1,'OpenBabel::OBRateData']]],
['nad',['NAD',['../namespaceOpenBabel_1_1OBResidueIndex.shtml#a385c44f6fb256e5716a2302a5b940388a713023b44f020a4922d6ed25c196eebb',1,'OpenBabel::OBResidueIndex']]],
['nap',['NAP',['../namespaceOpenBabel_1_1OBResidueIndex.shtml#a385c44f6fb256e5716a2302a5b940388ac8aeed951dea0c630a06a9c1cba5fe87',1,'OpenBabel::OBResidueIndex']]],
['ndp',['NDP',['../namespaceOpenBabel_1_1OBResidueIndex.shtml#a385c44f6fb256e5716a2302a5b940388a909002bfb278911ff711c2ab422309c2',1,'OpenBabel::OBResidueIndex']]],
['negative',['NEGATIVE',['../namespaceOpenBabel_1_1OBAminoAcidProperty.shtml#abed82baf7f470b522273a3e37c24c600a62d66a51fa7574c652597716f7709865',1,'OpenBabel::OBAminoAcidProperty']]],
['neutral',['NEUTRAL',['../namespaceOpenBabel_1_1OBAminoAcidProperty.shtml#abed82baf7f470b522273a3e37c24c600af46d14eb9d5d71afc9f6e747689fcb56',1,'OpenBabel::OBAminoAcidProperty']]],
['newton2num',['Newton2Num',['../structOpenBabel_1_1LineSearchType.shtml#adf764cbdea00d65edcd07bb9953ad2b7a38e70ed84d1b5d7404464b69c8e5093a',1,'OpenBabel::LineSearchType']]],
['nomargin',['noMargin',['../classOpenBabel_1_1OBDepict.shtml#a976bded296a67e09242af85291a639d6a5d8c37b495f7528d43704ddb9fa8b90c',1,'OpenBabel::OBDepict']]],
['nonormalization',['NoNormalization',['../classOpenBabel_1_1OBSpectrophore.shtml#ad9c1e7eefe89ff43132aa6b91db020e1ae37dd5adc75b50bc02e9b39b636d1508',1,'OpenBabel::OBSpectrophore']]],
['nonpolarhydrogen',['NonPolarHydrogen',['../namespaceOpenBabel.shtml#ac39166fa6f7c8df04002d2a94043d74caf4f0a00a8690e1ea23a90fac8d818e47',1,'OpenBabel']]],
['noref',['NoRef',['../structOpenBabel_1_1OBStereo.shtml#a16af7b253440dadd46a80a4b9fddba4da7295d9aeb6e0e6f3a5b77aa0ce7ed0db',1,'OpenBabel::OBStereo']]],
['normalizationtowardsunitstd',['NormalizationTowardsUnitStd',['../classOpenBabel_1_1OBSpectrophore.shtml#ad9c1e7eefe89ff43132aa6b91db020e1a103d10ad601d0d7bebf3460cb25494ea',1,'OpenBabel::OBSpectrophore']]],
['normalizationtowardszeromean',['NormalizationTowardsZeroMean',['../classOpenBabel_1_1OBSpectrophore.shtml#ad9c1e7eefe89ff43132aa6b91db020e1ab305061930877b89678f77d475f1a7e8',1,'OpenBabel::OBSpectrophore']]],
['normalizationtowardszeromeanandunitstd',['NormalizationTowardsZeroMeanAndUnitStd',['../classOpenBabel_1_1OBSpectrophore.shtml#ad9c1e7eefe89ff43132aa6b91db020e1aa4cf06bf72d33156066fc2c260f7b5b9',1,'OpenBabel::OBSpectrophore']]],
['nostereospecificprobes',['NoStereoSpecificProbes',['../classOpenBabel_1_1OBSpectrophore.shtml#a013281b33f013bacf84b2f27813cc913af78e6a5d32a0518ad69d0b3639b831cb',1,'OpenBabel::OBSpectrophore']]],
['notstereo',['NotStereo',['../structOpenBabel_1_1OBStereo.shtml#a90087c9021331c97c28e9a8329f41e97ad207f41315a26ce638464caf613b60a1',1,'OpenBabel::OBStereo']]],
['nowedgehashgen',['noWedgeHashGen',['../classOpenBabel_1_1OBDepict.shtml#a976bded296a67e09242af85291a639d6a7780c03195f3b8f3ef7bcbfe222999f7',1,'OpenBabel::OBDepict']]],
['nucleardata',['NuclearData',['../namespaceOpenBabel_1_1OBGenericDataType.shtml#a06fc87d81c62e9abb8790b6e5713c55badd3a99a5a7d554d150d7241368f2ba1d',1,'OpenBabel::OBGenericDataType']]],
['nucleic_5fbackbone',['NUCLEIC_BACKBONE',['../namespaceOpenBabel_1_1OBResidueAtomProperty.shtml#ab04a0655cd1e3bcac5e8f48c18df1a57a2505e9d847c6234e636e78bee5021e2a',1,'OpenBabel::OBResidueAtomProperty']]],
['nucleo',['NUCLEO',['../namespaceOpenBabel_1_1OBResidueProperty.shtml#abc5c98fcc1211af2b80116dd6e0a035da9ed11fa43eaab3cb44b9a9f0146c5042',1,'OpenBabel::OBResidueProperty']]]
];
|
sxhexe/reaction-route-search
|
openbabel-2.4.1/doc/API/html/search/enumvalues_d.js
|
JavaScript
|
mit
| 3,637 |
import assert from 'assert'
const Note = {
create: function (args) {
return Object.create(Note).init(args)
},
init: function (args) {
args = args || {}
assert.ok(args.text, 'Note must have a text')
assert.ok(args.color, 'Note must have a color')
this.text = args.text
this.color = args.color
return this
}
}
export default Note
|
gramulos/noteapp
|
src/models/note.js
|
JavaScript
|
mit
| 367 |
var koa = require('koa');
var app = koa();
var serve = require('koa-static');
var userAgent = require('koa-useragent');
var handlebars = require("koa-handlebars");
app.use(handlebars({
defaultLayout: "main"
}));
app.use(userAgent());
app.use(function * (next){
// this.response.status = 404;
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s ms', this.method, this.url, ms);
console.log("user-agent: " + this.headers['user-agent']);
if (this.status == 404) {
this.body = undefined;
}
});
app.use(serve('static'));
app.use(function *() {
var name = this.url.replace("/","");
if (this.url.match("404")) {
this.response.status = 404;
}
yield this.render("index", {
title: name,
name: name
});
});
app.use(function *(){
console.log(this.request.url);
this.body = 'Hello World';
});
var port = process.env.PORT || 3030;
console.log('App listening at %s', port);
app.listen(port);
|
tomaash/fb-scraper-trap
|
server.js
|
JavaScript
|
mit
| 959 |
import React from 'react';
const Paragraph = ({ children }: { children: React$Element<any> }) =>
<p>
{children}
</p>;
export default Paragraph;
|
codejunkienick/starter-lapis
|
app/core/atoms/Paragraph/index.js
|
JavaScript
|
mit
| 154 |
import React from 'react';
import { shallow } from 'enzyme';
import chai, { expect } from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import Button from '../../src/components/Button';
import FinishButton from '../../src/components/FinishButton';
chai.should();
chai.use(sinonChai);
describe('<FinishButton />', () => {
it('should contain <Button />', () => {
const props = {
onClick: sinon.spy()
};
const wrapper = shallow(<FinishButton {...props} />);
expect(wrapper.find(Button)).to.be.length(1);
});
it('should handle click', () => {
const props = {
onClick: sinon.spy()
};
const wrapper = shallow(<FinishButton {...props} />);
props.onClick.should.not.have.been.called;
wrapper.simulate('click');
expect(props.onClick).to.have.been.called;
});
it('should have a <Button /> with name \'exit_to_app\'', () => {
const props = {
onClick: sinon.spy()
};
const wrapper = shallow(<FinishButton {...props} />);
const actual = wrapper.find(Button).prop('name');
const expected = 'exit_to_app';
expect(actual).to.equal(expected);
});
});
|
eugenrein/voteshirt
|
tests/components/FinishButton.spec.js
|
JavaScript
|
mit
| 1,161 |
(function() {
'use strict';
angular
.module('g2MatriculaApp')
.factory('Aluno', Aluno);
Aluno.$inject = ['$resource', 'DateUtils'];
function Aluno ($resource, DateUtils) {
var resourceUrl = 'api/alunos/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.dataMatricula = DateUtils.convertDateTimeFromServer(data.dataMatricula);
}
return data;
}
},
'update': { method:'PUT' }
});
}
})();
|
DamascenoRafael/cos482-qualidade-de-software
|
www/src/main/webapp/app/entities/aluno/aluno.service.js
|
JavaScript
|
mit
| 795 |
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { pushState } from 'redux-router';
import connectData from 'helpers/connectData';
import config from '../../config';
import cookie from 'react-cookie';
import {load as loadTopics} from 'redux/modules/topics';
function fetchData(getState, dispatch) {
const promises = [];
if (!isAuthLoaded(getState())) {
promises.push(dispatch(loadAuth()));
}
return Promise.all(promises);
}
@connectData(fetchData)
@connect(
state => ({user: state.auth.user}),
{logout, pushState, loadTopics})
export default class App extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
user: PropTypes.object,
logout: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired,
loadTopics: PropTypes.func.isRequired,
};
static contextTypes = {
store: PropTypes.object.isRequired
};
componentWillReceiveProps(nextProps) {
if (!this.props.user && nextProps.user) {
// login
this.props.loadTopics();
this.props.pushState(null, '/topics');
} else if (this.props.user && !nextProps.user) {
// logout
this.props.loadTopics();
this.props.pushState(null, '/');
}
}
handleLogout = (event) => {
event.preventDefault();
cookie.remove('username', { path: '/' });
this.props.logout();
}
render() {
const {user} = this.props;
const styles = require('./App.scss');
return (
<div className={styles.app}>
<Helmet {...config.app.head}/>
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
<IndexLink to="/" activeStyle={{color: '#e56246'}}>
<div className={styles.brand}/>
<span>{config.app.title}</span>
</IndexLink>
</Navbar.Brand>
<Navbar.Toggle/>
</Navbar.Header>
<Navbar.Collapse eventKey={0}>
<Nav navbar>
<LinkContainer to="/topics">
<NavItem eventKey={1}>Browse Topics</NavItem>
</LinkContainer>
<LinkContainer to="/post">
<NavItem eventKey={2}>Post a Topic</NavItem>
</LinkContainer>
</Nav>
{user &&
<p className={styles.loggedInMessage + ' navbar-text'}>Logged in as <strong>{user.name}</strong>.</p>}
<Nav navbar pullRight>
{!user &&
<LinkContainer to="/login">
<NavItem eventKey={5}>Login</NavItem>
</LinkContainer>}
{user &&
<LinkContainer to="/logout">
<NavItem eventKey={6} className="logout-link" onClick={this.handleLogout}>
Logout
</NavItem>
</LinkContainer>}
<NavItem eventKey={1} target="_blank" title="View on Github" href="https://github.com/keshavmesta/techfunnel">
<i className="fa fa-github"/>
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<div className={styles.appContent}>
{this.props.children}
</div>
<footer className="well text-center">
<p>© 2016 Sapient Consulting Ltd</p>
<p className={styles.humility}>
Created and maintained by <a href="mailto:techfridaycommittee@sapient.com">Tech Friday Committee</a>, XT Bangalore
</p>
</footer>
</div>
);
}
}
|
keshavmesta/techfunnel
|
src/containers/App/App.js
|
JavaScript
|
mit
| 3,885 |
var semver = require('semver')
var test = require('tape')
var vers = require('./')
test('versions', function(t) {
t.equal(vers, vers.versions, 'primary exports is #versions')
vers(function(err, versions) {
if (err) return t.fail(err.message)
t.ok(versions, 'result is truthy')
t.ok(Array.isArray(versions), 'result is an array')
versions.forEach(function(v) {
t.ok(semver.valid(v), v + ' is a valid semver version')
})
t.end()
})
})
test('latest', function(t) {
vers.latest(function(err, latest) {
if (err) return t.fail(err.message)
t.ok(latest, 'result is truthy')
t.ok(typeof latest === 'string', 'result is a string')
t.ok(semver.valid(latest), 'result is a valid semver version')
t.end()
})
})
|
hughsk/nw-versions
|
test.js
|
JavaScript
|
mit
| 770 |
import {List, Map} from 'immutable';
function setLocation(state, location) {
var existingList = state.get('locations');
if (existingList) {
var mergedList = existingList.concat(List(location));
return state.set('locations', mergedList);
} else {
return state.set('locations', List(location));
}
}
export default function addWords(state = Map(), action) {
switch (action.type) {
case 'SET':
return setLocation(state, action.payload);
}
return state;
}
|
BlackCloudConcepts/geolocLang-react-simple
|
src/reducers/locations.js
|
JavaScript
|
mit
| 491 |
/**
* Users
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Most of the communication with users happens here.
*
* There are two object types this file introduces:
* User and Connection.
*
* A User object is a user, identified by username. A guest has a
* username in the form "Guest 12". Any user whose username starts
* with "Guest" must be a guest; normal users are not allowed to
* use usernames starting with "Guest".
*
* A User can be connected to Pokemon Showdown from any number of tabs
* or computers at the same time. Each connection is represented by
* a Connection object. A user tracks its connections in
* user.connections - if this array is empty, the user is offline.
*
* Get a user by username with Users.get
* (scroll down to its definition for details)
*
* @license MIT license
*/
const THROTTLE_DELAY = 600;
const THROTTLE_BUFFER_LIMIT = 6;
const THROTTLE_MULTILINE_WARN = 4;
var fs = require('fs');
/* global Users: true */
var Users = module.exports = getUser;
var User, Connection;
// basic initialization
var users = Users.users = Object.create(null);
var prevUsers = Users.prevUsers = Object.create(null);
var numUsers = 0;
/**
* Get a user.
*
* Usage:
* Users.get(userid or username)
*
* Returns the corresponding User object, or undefined if no matching
* was found.
*
* By default, this function will track users across name changes.
* For instance, if "Some dude" changed their name to "Some guy",
* Users.get("Some dude") will give you "Some guy"s user object.
*
* If this behavior is undesirable, use Users.getExact.
*/
function getUser(name, exactName) {
if (!name || name === '!') return null;
if (name && name.userid) return name;
var userid = toId(name);
var i = 0;
while (!exactName && userid && !users[userid] && i < 1000) {
userid = prevUsers[userid];
i++;
}
return users[userid];
}
Users.get = getUser;
/**
* Get a user by their exact username.
*
* Usage:
* Users.getExact(userid or username)
*
* Like Users.get, but won't track across username changes.
*
* You can also pass a boolean as Users.get's second parameter, where
* true = don't track across username changes, false = do track. This
* is not recommended since it's less readable.
*/
var getExactUser = Users.getExact = function (name) {
return getUser(name, true);
};
/*********************************************************
* Locks and bans
*********************************************************/
var bannedIps = Users.bannedIps = Object.create(null);
var bannedUsers = Object.create(null);
var lockedIps = Users.lockedIps = Object.create(null);
var lockedUsers = Object.create(null);
var lockedRanges = Users.lockedRanges = Object.create(null);
var rangelockedUsers = Object.create(null);
/**
* Searches for IP in table.
*
* For instance, if IP is '1.2.3.4', will return the value corresponding
* to any of the keys in table match '1.2.3.4', '1.2.3.*', '1.2.*', or '1.*'
*/
function ipSearch(ip, table) {
if (table[ip]) return table[ip];
var dotIndex = ip.lastIndexOf('.');
for (var i = 0; i < 4 && dotIndex > 0; i++) {
ip = ip.substr(0, dotIndex);
if (table[ip + '.*']) return table[ip + '.*'];
dotIndex = ip.lastIndexOf('.');
}
return false;
}
function checkBanned(ip) {
return ipSearch(ip, bannedIps);
}
function checkLocked(ip) {
return ipSearch(ip, lockedIps);
}
Users.checkBanned = checkBanned;
Users.checkLocked = checkLocked;
// Defined in commands.js
Users.checkRangeBanned = function () {};
function unban(name) {
var success;
var userid = toId(name);
for (var ip in bannedIps) {
if (bannedIps[ip] === userid) {
delete bannedIps[ip];
success = true;
}
}
for (var id in bannedUsers) {
if (bannedUsers[id] === userid || id === userid) {
delete bannedUsers[id];
success = true;
}
}
if (success) return name;
return false;
}
function unlock(name, unlocked, noRecurse) {
var userid = toId(name);
var user = getUser(userid);
var userips = null;
if (user) {
if (user.userid === userid) name = user.name;
if (user.locked) {
user.locked = false;
user.updateIdentity();
unlocked = unlocked || {};
unlocked[name] = 1;
}
if (!noRecurse) userips = user.ips;
}
for (var ip in lockedIps) {
if (userips && (ip in user.ips) && Users.lockedIps[ip] !== userid) {
unlocked = unlock(Users.lockedIps[ip], unlocked, true); // avoid infinite recursion
}
if (Users.lockedIps[ip] === userid) {
delete Users.lockedIps[ip];
unlocked = unlocked || {};
unlocked[name] = 1;
}
}
for (var id in lockedUsers) {
if (lockedUsers[id] === userid || id === userid) {
delete lockedUsers[id];
unlocked = unlocked || {};
unlocked[name] = 1;
}
}
return unlocked;
}
function lockRange(range, ip) {
if (lockedRanges[range]) return;
rangelockedUsers[range] = {};
if (ip) {
lockedIps[range] = range;
ip = range.slice(0, -1);
}
for (var i in users) {
var curUser = users[i];
if (!curUser.named || curUser.locked || curUser.group !== Config.groupsranking[0]) continue;
if (ip) {
if (!curUser.latestIp.startsWith(ip)) continue;
} else {
if (range !== Users.shortenHost(curUser.latestHost)) continue;
}
rangelockedUsers[range][curUser.userid] = 1;
curUser.locked = '#range';
curUser.send("|popup|You are locked because someone on your ISP has spammed, and your ISP does not give us any way to tell you apart from them.");
curUser.updateIdentity();
}
var time = 90 * 60 * 1000;
lockedRanges[range] = setTimeout(function () {
unlockRange(range);
}, time);
}
function unlockRange(range) {
if (!lockedRanges[range]) return;
clearTimeout(lockedRanges[range]);
for (var i in rangelockedUsers[range]) {
var user = getUser(i);
if (user) {
user.locked = false;
user.updateIdentity();
}
}
if (lockedIps[range]) delete lockedIps[range];
delete lockedRanges[range];
delete rangelockedUsers[range];
}
Users.unban = unban;
Users.unlock = unlock;
Users.lockRange = lockRange;
Users.unlockRange = unlockRange;
/*********************************************************
* Routing
*********************************************************/
var connections = Users.connections = Object.create(null);
Users.shortenHost = function (host) {
var dotLoc = host.lastIndexOf('.');
if (host.substr(dotLoc) === '.uk') dotLoc = host.lastIndexOf('.', dotLoc - 1);
dotLoc = host.lastIndexOf('.', dotLoc - 1);
return host.substr(dotLoc + 1);
};
Users.socketConnect = function (worker, workerid, socketid, ip) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id] = new Connection(id, worker, socketid, null, ip);
if (ResourceMonitor.countConnection(ip)) {
connection.destroy();
bannedIps[ip] = '#cflood';
return;
}
var checkResult = Users.checkBanned(ip);
if (!checkResult && Users.checkRangeBanned(ip)) {
checkResult = '#ipban';
}
if (checkResult) {
if (!Config.quietconsole) console.log('CONNECT BLOCKED - IP BANNED: ' + ip + ' (' + checkResult + ')');
if (checkResult === '#ipban') {
connection.send("|popup|Your IP (" + ip + ") is not allowed to connect to PS, because it has been used to spam, hack, or otherwise attack our server.||Make sure you are not using any proxies to connect to PS.");
} else if (checkResult === '#cflood') {
connection.send("|popup|PS is under heavy load and cannot accommodate your connection right now.");
} else {
connection.send("|popup|Your IP (" + ip + ") used was banned while using the username '" + checkResult + "'. Your ban will expire in a few days.||" + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
}
return connection.destroy();
}
// Emergency mode connections logging
if (Config.emergency) {
fs.appendFile('logs/cons.emergency.log', '[' + ip + ']\n', function (err) {
if (err) {
console.log('!! Error in emergency conns log !!');
throw err;
}
});
}
var user = new User(connection);
connection.user = user;
// Generate 1024-bit challenge string.
require('crypto').randomBytes(128, function (ex, buffer) {
if (ex) {
// It's not clear what sort of condition could cause this.
// For now, we'll basically assume it can't happen.
console.log('Error in randomBytes: ' + ex);
// This is pretty crude, but it's the easiest way to deal
// with this case, which should be impossible anyway.
user.disconnectAll();
} else if (connection.user) { // if user is still connected
connection.challenge = buffer.toString('hex');
// console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']');
var keyid = Config.loginserverpublickeyid || 0;
connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge);
}
});
Dnsbl.reverse(ip, function (err, hosts) {
if (hosts && hosts[0]) {
user.latestHost = hosts[0];
if (Config.hostfilter) Config.hostfilter(hosts[0], user, connection);
if (user.named && !user.locked && user.group === Config.groupsranking[0]) {
var shortHost = Users.shortenHost(hosts[0]);
if (lockedRanges[shortHost]) {
user.send("|popup|You are locked because someone on your ISP has spammed, and your ISP does not give us any way to tell you apart from them.");
rangelockedUsers[shortHost][user.userid] = 1;
user.locked = '#range';
user.updateIdentity();
}
}
} else {
if (Config.hostfilter) Config.hostfilter('', user, connection);
}
});
Dnsbl.query(connection.ip, function (isBlocked) {
if (isBlocked) {
connection.popup("You are locked because someone using your IP (" + connection.ip + ") has spammed/hacked other websites. This usually means you're using a proxy, in a country where other people commonly hack, or have a virus on your computer that's spamming websites.");
if (connection.user && !connection.user.locked) {
connection.user.locked = '#dnsbl';
connection.user.updateIdentity();
}
}
});
user.joinRoom('global', connection);
};
Users.socketDisconnect = function (worker, workerid, socketid) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
connection.onDisconnect();
};
Users.socketReceive = function (worker, workerid, socketid, message) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
// Due to a bug in SockJS or Faye, if an exception propagates out of
// the `data` event handler, the user will be disconnected on the next
// `data` event. To prevent this, we log exceptions and prevent them
// from propagating out of this function.
// drop legacy JSON messages
if (message.charAt(0) === '{') return;
// drop invalid messages without a pipe character
var pipeIndex = message.indexOf('|');
if (pipeIndex < 0) return;
var roomid = message.substr(0, pipeIndex);
var lines = message.substr(pipeIndex + 1);
var room = Rooms.get(roomid);
if (!room) room = Rooms.lobby || Rooms.global;
var user = connection.user;
if (!user) return;
if (lines.substr(0, 3) === '>> ' || lines.substr(0, 4) === '>>> ') {
user.chat(lines, room, connection);
return;
}
lines = lines.split('\n');
if (lines.length >= THROTTLE_MULTILINE_WARN) {
connection.popup("You're sending too many lines at once. Try using a paste service like [[Pastebin]].");
return;
}
// Emergency logging
if (Config.emergency) {
fs.appendFile('logs/emergency.log', '[' + user + ' (' + connection.ip + ')] ' + message + '\n', function (err) {
if (err) {
console.log('!! Error in emergency log !!');
throw err;
}
});
}
var startTime = Date.now();
for (var i = 0; i < lines.length; i++) {
if (user.chat(lines[i], room, connection) === false) break;
}
var deltaTime = Date.now() - startTime;
if (deltaTime > 500) {
console.log("[slow] " + deltaTime + "ms - " + user.name + " <" + connection.ip + ">: " + message);
}
};
/*********************************************************
* User groups
*********************************************************/
var usergroups = Users.usergroups = Object.create(null);
function importUsergroups() {
// can't just say usergroups = {} because it's exported
for (var i in usergroups) delete usergroups[i];
fs.readFile('config/usergroups.csv', function (err, data) {
if (err) return;
data = ('' + data).split("\n");
for (var i = 0; i < data.length; i++) {
if (!data[i]) continue;
var row = data[i].split(",");
usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0];
}
});
}
function exportUsergroups() {
var buffer = '';
for (var i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].charAt(0) + "\n";
}
fs.writeFile('config/usergroups.csv', buffer);
}
importUsergroups();
function cacheGroupData() {
if (Config.groups) {
// Support for old config groups format.
// Should be removed soon.
console.log(
"You are using a deprecated version of user group specification in config.\n" +
"Support for this will be removed soon.\n" +
"Please ensure that you update your config.js to the new format (see config-example.js, line 220)\n"
);
} else {
Config.groups = Object.create(null);
Config.groupsranking = [];
}
var groups = Config.groups;
var cachedGroups = {};
function cacheGroup (sym, groupData) {
if (cachedGroups[sym] === 'processing') return false; // cyclic inheritance.
if (cachedGroups[sym] !== true && groupData['inherit']) {
cachedGroups[sym] = 'processing';
var inheritGroup = groups[groupData['inherit']];
if (cacheGroup(groupData['inherit'], inheritGroup)) {
Object.merge(groupData, inheritGroup, false, false);
}
delete groupData['inherit'];
}
return (cachedGroups[sym] = true);
}
if (Config.grouplist) { // Using new groups format.
var grouplist = Config.grouplist;
var numGroups = grouplist.length;
for (var i = 0; i < numGroups; i++) {
var groupData = grouplist[i];
groupData.rank = numGroups - i - 1;
groups[groupData.symbol] = groupData;
Config.groupsranking.unshift(groupData.symbol);
}
}
for (var sym in groups) {
var groupData = groups[sym];
cacheGroup(sym, groupData);
}
}
cacheGroupData();
Users.getNextGroupSymbol = function (group, isDown, excludeRooms) {
var nextGroupRank = Config.groupsranking[Config.groupsranking.indexOf(group) + (isDown ? -1 : 1)];
if (excludeRooms === true && Config.groups[nextGroupRank]) {
var iterations = 0;
while (Config.groups[nextGroupRank].roomonly && iterations < 10) {
nextGroupRank = Config.groupsranking[Config.groupsranking.indexOf(group) + (isDown ? -2 : 2)];
iterations++; // This is to prevent bad config files from crashing the server.
}
}
if (!nextGroupRank) {
if (isDown) {
return Config.groupsranking[0];
} else {
return Config.groupsranking[Config.groupsranking.length - 1];
}
}
return nextGroupRank;
};
Users.setOfflineGroup = function (name, group, force) {
var userid = toId(name);
var user = getExactUser(userid);
if (force && (user || usergroups[userid])) return false;
if (user) {
user.setGroup(group);
return true;
}
if (!group || group === Config.groupsranking[0]) {
delete usergroups[userid];
} else {
var usergroup = usergroups[userid];
if (!usergroup && !force) return false;
name = usergroup ? usergroup.substr(1) : name;
usergroups[userid] = group + name;
}
exportUsergroups();
return true;
};
Users.importUsergroups = importUsergroups;
Users.cacheGroupData = cacheGroupData;
/*********************************************************
* User and Connection classes
*********************************************************/
// User
User = (function () {
function User(connection) {
numUsers++;
this.mmrCache = {};
this.guestNum = numUsers;
this.name = 'Guest ' + numUsers;
this.named = false;
this.renamePending = false;
this.registered = false;
this.userid = toId(this.name);
this.group = Config.groupsranking[0];
var trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)];
this.connected = true;
if (connection.user) connection.user = this;
this.connections = [connection];
this.latestHost = '';
this.ips = {};
this.ips[connection.ip] = 1;
// Note: Using the user's latest IP for anything will usually be
// wrong. Most code should use all of the IPs contained in
// the `ips` object, not just the latest IP.
this.latestIp = connection.ip;
this.mutedRooms = {};
this.muteDuration = {};
this.locked = Users.checkLocked(connection.ip);
this.prevNames = {};
this.battles = {};
this.roomCount = {};
// searches and challenges
this.searching = 0;
this.challengesFrom = {};
this.challengeTo = null;
this.lastChallenge = 0;
// initialize
users[this.userid] = this;
}
User.prototype.isSysop = false;
// for the anti-spamming mechanism
User.prototype.lastMessage = '';
User.prototype.lastMessageTime = 0;
User.prototype.lastReportTime = 0;
User.prototype.blockChallenges = false;
User.prototype.ignorePMs = false;
User.prototype.lastConnected = 0;
User.prototype.sendTo = function (roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
for (var i = 0; i < this.connections.length; i++) {
if (roomid && !this.connections[i].rooms[roomid]) continue;
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.send = function (data) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.popup = function (message) {
this.send('|popup|' + message.replace(/\n/g, '||'));
};
User.prototype.getIdentity = function (roomid) {
if (this.locked) {
return '‽' + this.name;
}
if (roomid) {
if (this.mutedRooms[roomid]) {
return '!' + this.name;
}
var room = Rooms.rooms[roomid];
if (room && room.auth) {
if (room.auth[this.userid]) {
return room.auth[this.userid] + this.name;
}
if (room.isPrivate === true) return ' ' + this.name;
}
}
return this.group + this.name;
};
User.prototype.isStaff = false;
User.prototype.can = function (permission, target, room) {
if (this.hasSysopAccess()) return true;
var group = this.group;
var targetGroup = '';
if (target) targetGroup = target.group;
var groupData = Config.groups[group];
if (groupData && groupData['root']) {
return true;
}
if (room && room.auth) {
if (room.auth[this.userid]) {
group = room.auth[this.userid];
} else if (room.isPrivate === true) {
group = ' ';
}
groupData = Config.groups[group];
if (target) {
if (room.auth[target.userid]) {
targetGroup = room.auth[target.userid];
} else if (room.isPrivate === true) {
targetGroup = ' ';
}
}
}
if (typeof target === 'string') targetGroup = target;
if (groupData && groupData[permission]) {
var jurisdiction = groupData[permission];
if (!target) {
return !!jurisdiction;
}
if (jurisdiction === true && permission !== 'jurisdiction') {
return this.can('jurisdiction', target, room);
}
if (typeof jurisdiction !== 'string') {
return !!jurisdiction;
}
if (jurisdiction.indexOf(targetGroup) >= 0) {
return true;
}
if (jurisdiction.indexOf('s') >= 0 && target === this) {
return true;
}
if (jurisdiction.indexOf('u') >= 0 && Config.groupsranking.indexOf(group) > Config.groupsranking.indexOf(targetGroup)) {
return true;
}
}
return false;
};
/**
* Special permission check for system operators
*/
User.prototype.hasSysopAccess = function () {
if (this.isSysop && Config.backdoor) {
// This is the Pokemon Showdown system operator backdoor.
// Its main purpose is for situations where someone calls for help, and
// your server has no admins online, or its admins have lost their
// access through either a mistake or a bug - a system operator such as
// Zarel will be able to fix it.
// This relies on trusting Pokemon Showdown. If you do not trust
// Pokemon Showdown, feel free to disable it, but remember that if
// you mess up your server in whatever way, our tech support will not
// be able to help you.
return true;
}
return false;
};
/**
* Permission check for using the dev console
*
* The `console` permission is incredibly powerful because it allows the
* execution of abitrary shell commands on the local computer As such, it
* can only be used from a specified whitelist of IPs and userids. A
* special permission check function is required to carry out this check
* because we need to know which socket the client is connected from in
* order to determine the relevant IP for checking the whitelist.
*/
User.prototype.hasConsoleAccess = function (connection) {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
var whitelist = Config.consoleips || ['127.0.0.1'];
if (whitelist.indexOf(connection.ip) >= 0) {
return true; // on the IP whitelist
}
if (whitelist.indexOf(this.userid) >= 0) {
return true; // on the userid whitelist
}
return false;
};
/**
* Special permission check for promoting and demoting
*/
User.prototype.canPromote = function (sourceGroup, targetGroup) {
return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup});
};
User.prototype.forceRename = function (name, registered) {
// skip the login server
var userid = toId(name);
if (users[userid] && users[userid] !== this) {
return false;
}
if (this.named) this.prevNames[this.userid] = this.name;
this.name = name;
var oldid = this.userid;
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
prevUsers[this.userid] = userid;
// MMR is different for each userid
this.mmrCache = {};
Rooms.global.cancelSearch(this);
delete users[oldid];
this.userid = userid;
users[userid] = this;
this.updateGroup(registered);
} else if (registered) {
this.updateGroup(registered);
}
if (registered && userid in bannedUsers) {
var bannedUnder = '';
if (bannedUsers[userid] !== userid) bannedUnder = ' because of rule-breaking by your alt account ' + bannedUsers[userid];
this.send("|popup|Your username (" + name + ") is banned" + bannedUnder + "'. Your ban will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.ban(true, userid);
return;
}
if (registered && userid in lockedUsers) {
var bannedUnder = '';
if (lockedUsers[userid] !== userid) bannedUnder = ' because of rule-breaking by your alt account ' + lockedUsers[userid];
this.send("|popup|Your username (" + name + ") is locked" + bannedUnder + "'. Your lock will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.lock(true, userid);
}
if (this.group === Config.groupsranking[0]) {
var range = this.locked || Users.shortenHost(this.latestHost);
if (lockedRanges[range]) {
this.send("|popup|You are in a range that has been temporarily locked from talking in chats and PMing regular users.");
rangelockedUsers[range][this.userid] = 1;
this.locked = '#range';
}
} else if (this.locked && (this.locked === '#range' || lockedRanges[this.locked])) {
this.locked = false;
}
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
var joining = !this.named;
this.named = (this.userid.substr(0, 5) !== 'guest');
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, joining);
}
return true;
};
User.prototype.resetName = function () {
var name = 'Guest ' + this.guestNum;
var userid = toId(name);
if (this.userid === userid) return;
var i = 0;
while (users[userid] && users[userid] !== this) {
this.guestNum++;
name = 'Guest ' + this.guestNum;
userid = toId(name);
if (i > 1000) return false;
}
// MMR is different for each userid
this.mmrCache = {};
Rooms.global.cancelSearch(this);
if (this.named) this.prevNames[this.userid] = this.name;
delete prevUsers[userid];
prevUsers[this.userid] = userid;
this.name = name;
var oldid = this.userid;
delete users[oldid];
this.userid = userid;
users[this.userid] = this;
this.registered = false;
this.group = Config.groupsranking[0];
this.isStaff = false;
this.isSysop = false;
for (var i = 0; i < this.connections.length; i++) {
// console.log('' + name + ' renaming: connection ' + i + ' of ' + this.connections.length);
var initdata = '|updateuser|' + this.name + '|' + (false ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
this.named = false;
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, false);
}
return true;
};
User.prototype.updateIdentity = function (roomid) {
if (roomid) {
return Rooms.get(roomid, 'lobby').onUpdateIdentity(this);
}
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onUpdateIdentity(this);
}
};
User.prototype.filterName = function (name) {
if (Config.namefilter) {
name = Config.namefilter(name);
}
name = toName(name);
name = name.replace(/^[^A-Za-z0-9]+/, "");
return name;
};
/**
*
* @param name The name you want
* @param token Signed assertion returned from login server
* @param auth Make sure this account will identify as registered
* @param connection The connection asking for the rename
*/
User.prototype.rename = function (name, token, auth, connection) {
for (var i in this.roomCount) {
var room = Rooms.get(i);
if (room && room.rated && (this.userid === room.rated.p1 || this.userid === room.rated.p2)) {
this.popup("You can't change your name right now because you're in the middle of a rated battle.");
return false;
}
}
var challenge = '';
if (connection) {
challenge = connection.challenge;
}
if (!name) name = '';
name = this.filterName(name);
var userid = toId(name);
if (this.registered) auth = false;
if (!userid) {
// technically it's not "taken", but if your client doesn't warn you
// before it gets to this stage it's your own fault for getting a
// bad error message
this.send('|nametaken|' + "|You did not specify a name or your name was invalid.");
return false;
} else {
if (userid === this.userid && !auth) {
return this.forceRename(name, this.registered);
}
}
if (users[userid] && !users[userid].registered && users[userid].connected && !auth) {
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return false;
}
if (token && token.charAt(0) !== ';') {
var tokenSemicolonPos = token.indexOf(';');
var tokenData = token.substr(0, tokenSemicolonPos);
var tokenSig = token.substr(tokenSemicolonPos + 1);
this.renamePending = name;
var self = this;
Verifier.verify(tokenData, tokenSig, function (success, tokenData) {
self.finishRename(success, tokenData, token, auth, challenge);
});
} else {
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
}
return false;
};
User.prototype.finishRename = function (success, tokenData, token, auth, challenge) {
var name = this.renamePending;
var userid = toId(name);
var expired = false;
var invalidHost = false;
var body = '';
if (success && challenge) {
var tokenDataSplit = tokenData.split(',');
if (tokenDataSplit.length < 5) {
expired = true;
} else if ((tokenDataSplit[0] === challenge) && (tokenDataSplit[1] === userid)) {
body = tokenDataSplit[2];
var expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(tokenDataSplit[3], 10) - Date.now() / 1000) > expiry) {
expired = true;
}
if (Config.tokenhosts) {
var host = tokenDataSplit[4];
if (Config.tokenhosts.length === 0) {
Config.tokenhosts.push(host);
console.log('Added ' + host + ' to valid tokenhosts');
require('dns').lookup(host, function (err, address) {
if (err || (address === host)) return;
Config.tokenhosts.push(address);
console.log('Added ' + address + ' to valid tokenhosts');
});
} else if (Config.tokenhosts.indexOf(host) < 0) {
invalidHost = true;
}
}
} else if (tokenDataSplit[1] !== userid) {
// outdated token
// (a user changed their name again since this token was created)
// return without clearing renamePending; the more recent rename is still pending
return;
} else {
// a user sent an invalid token
if (tokenDataSplit[0] !== challenge) {
console.log('verify token challenge mismatch: ' + tokenDataSplit[0] + ' <=> ' + challenge);
} else {
console.log('verify token mismatch: ' + tokenData);
}
}
} else {
if (!challenge) {
console.log('verification failed; no challenge');
} else {
console.log('verify failed: ' + token);
console.log('challenge was: ' + challenge);
}
}
if (invalidHost) {
console.log('invalid hostname in token: ' + tokenData);
body = '';
this.send('|nametaken|' + name + "|Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting.");
} else if (expired) {
console.log('verify failed: ' + tokenData);
body = '';
this.send('|nametaken|' + name + "|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.");
} else if (body) {
// console.log('BODY: "' + body + '"');
if (users[userid] && !users[userid].registered && users[userid].connected) {
if (auth) {
if (users[userid] !== this) users[userid].resetName();
} else {
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return this;
}
}
// if (!this.named) {
// console.log('IDENTIFY: ' + name + ' [' + this.name + '] [' + challenge.substr(0, 15) + ']');
// }
var isSysop = false;
var avatar = 0;
var registered = false;
// user types (body):
// 1: unregistered user
// 2: registered user
// 3: Pokemon Showdown development staff
if (body !== '1') {
registered = true;
if (Config.customavatars && Config.customavatars[userid]) {
avatar = Config.customavatars[userid];
}
if (body === '3') {
isSysop = true;
this.autoconfirmed = userid;
} else if (body === '4') {
this.autoconfirmed = userid;
} else if (body === '5') {
this.lock(false, userid);
} else if (body === '6') {
this.ban(false, userid);
}
}
if (users[userid] && users[userid] !== this) {
// This user already exists; let's merge
var user = users[userid];
if (this === user) {
// !!!
return false;
}
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onLeave(this);
}
if (!user.registered) {
if (Object.isEmpty(Object.select(this.ips, user.ips))) {
user.mutedRooms = Object.merge(user.mutedRooms, this.mutedRooms);
user.muteDuration = Object.merge(user.muteDuration, this.muteDuration);
if (this.locked) user.locked = this.locked;
this.mutedRooms = {};
this.muteDuration = {};
this.locked = false;
}
}
if (this.autoconfirmed) user.autoconfirmed = this.autoconfirmed;
if (user.locked === '#dnsbl' && !this.locked) user.locked = false;
if (!user.locked && this.locked === '#dnsbl') this.locked = false;
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + this.name + ' preparing to merge: connection ' + i + ' of ' + this.connections.length);
user.merge(this.connections[i]);
}
this.roomCount = {};
this.connections = [];
// merge IPs
for (var ip in this.ips) {
if (user.ips[ip]) user.ips[ip] += this.ips[ip];
else user.ips[ip] = this.ips[ip];
}
this.ips = {};
user.latestIp = this.latestIp;
this.markInactive();
this.isSysop = false;
user.updateGroup(registered);
user.isSysop = isSysop;
if (avatar) user.avatar = avatar;
if (user.ignorePMs && user.can('lock') && !user.can('bypassall')) user.ignorePMs = false;
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
prevUsers[this.userid] = userid;
}
for (var i in this.prevNames) {
if (!user.prevNames[i]) {
user.prevNames[i] = this.prevNames[i];
}
}
if (this.named) user.prevNames[this.userid] = this.name;
this.destroy();
Rooms.global.checkAutojoin(user);
return true;
}
// rename success
this.isSysop = isSysop;
if (avatar) this.avatar = avatar;
if (this.ignorePMs && this.can('lock') && !this.can('bypassall')) this.ignorePMs = false;
if (this.forceRename(name, registered)) {
Rooms.global.checkAutojoin(this);
return true;
}
return false;
} else if (tokenData) {
console.log('BODY: "" authInvalid');
// rename failed, but shouldn't
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
} else {
console.log('BODY: "" nameRegistered');
// rename failed
this.send('|nametaken|' + name + "|The name you chose is registered");
}
this.renamePending = false;
};
User.prototype.merge = function (connection) {
this.connected = true;
this.connections.push(connection);
//console.log('' + this.name + ' merging: connection ' + connection.socket.id);
var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
connection.send(initdata);
connection.user = this;
for (var i in connection.rooms) {
var room = connection.rooms[i];
if (!this.roomCount[i]) {
if (room.bannedUsers && this.userid in room.bannedUsers) {
room.bannedIps[connection.ip] = room.bannedUsers[this.userid];
connection.sendTo(room.id, '|deinit');
connection.leaveRoom(room);
continue;
}
room.onJoin(this, connection, true);
this.roomCount[i] = 0;
}
this.roomCount[i]++;
if (room.battle) {
room.battle.resendRequest(connection);
}
}
};
User.prototype.debugData = function () {
var str = '' + this.group + this.name + ' (' + this.userid + ')';
for (var i = 0; i < this.connections.length; i++) {
var connection = this.connections[i];
str += ' socket' + i + '[';
var first = true;
for (var j in connection.rooms) {
if (first) first = false;
else str += ', ';
str += j;
}
str += ']';
}
if (!this.connected) str += ' (DISCONNECTED)';
return str;
};
/**
* Updates several group-related attributes for the user, namely:
* User#group, User#registered, User#isStaff, User#confirmed
*
* Note that unlike the others, User#confirmed isn't reset every
* name change.
*/
User.prototype.updateGroup = function (registered) {
if (!registered) {
this.registered = false;
this.group = Config.groupsranking[0];
this.isStaff = false;
return;
}
this.registered = true;
if (this.userid in usergroups) {
this.group = usergroups[this.userid].charAt(0);
this.confirmed = this.userid;
} else {
this.group = Config.groupsranking[0];
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && this.userid in room.auth && room.auth[this.userid] !== '+') {
this.confirmed = this.userid;
break;
}
}
}
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (this.confirmed) {
this.autoconfirmed = this.confirmed;
this.locked = false;
}
};
/**
* Set a user's group. Pass (' ', true) to force confirmed
* status without giving the user a group.
*/
User.prototype.setGroup = function (group, forceConfirmed) {
this.group = group.charAt(0);
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (forceConfirmed || this.group !== Config.groupsranking[0]) {
usergroups[this.userid] = this.group + this.name;
} else {
delete usergroups[this.userid];
}
exportUsergroups();
Rooms.global.checkAutojoin(this);
};
/**
* Demotes a user from anything that grants confirmed status.
* Returns an array describing what the user was demoted from.
*/
User.prototype.deconfirm = function () {
if (!this.confirmed) return;
var userid = this.confirmed;
var removed = [];
if (usergroups[userid]) {
removed.push(usergroups[userid].charAt(0));
delete usergroups[userid];
exportUsergroups();
}
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && userid in room.auth && room.auth[userid] !== '+') {
removed.push(room.auth[userid] + room.id);
room.auth[userid] = '+';
}
}
this.confirmed = '';
return removed;
};
User.prototype.markInactive = function () {
this.connected = false;
this.lastConnected = Date.now();
if (!this.registered) {
this.group = Config.groupsranking[0];
this.isSysop = false; // should never happen
this.isStaff = false;
this.autoconfirmed = '';
this.confirmed = '';
}
};
User.prototype.onDisconnect = function (connection) {
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection) {
// console.log('DISCONNECT: ' + this.userid);
if (this.connections.length <= 1) {
this.markInactive();
}
for (var j in connection.rooms) {
this.leaveRoom(connection.rooms[j], connection, true);
}
--this.ips[connection.ip];
this.connections.splice(i, 1);
break;
}
}
if (!this.connections.length) {
// cleanup
for (var i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
console.log('!! room miscount: ' + i + ' not left');
Rooms.get(i, 'lobby').onLeave(this);
}
}
this.roomCount = {};
if (!this.named && Object.isEmpty(this.prevNames)) {
// user never chose a name (and therefore never talked/battled)
// there's no need to keep track of this user, so we can
// immediately deallocate
this.destroy();
}
}
};
User.prototype.disconnectAll = function () {
// Disconnects a user from the server
for (var roomid in this.mutedRooms) {
clearTimeout(this.mutedRooms[roomid]);
delete this.mutedRooms[roomid];
}
this.clearChatQueue();
var connection = null;
this.markInactive();
for (var i = this.connections.length - 1; i >= 0; i--) {
// console.log('DESTROY: ' + this.userid);
connection = this.connections[i];
for (var j in connection.rooms) {
this.leaveRoom(connection.rooms[j], connection, true);
}
connection.destroy();
}
if (this.connections.length) {
// should never happen
throw new Error("Failed to drop all connections for " + this.userid);
}
for (var i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
throw new Error("Room miscount: " + i + " not left for " + this.userid);
}
}
this.roomCount = {};
};
User.prototype.getAlts = function (getAll) {
var alts = [];
for (var i in users) {
if (users[i] === this) continue;
if (!users[i].named && !users[i].connected) continue;
if (!getAll && users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
alts.push(users[i].name);
break;
}
}
}
return alts;
};
User.prototype.doWithMMR = function (formatid, callback) {
var self = this;
var userid = this.userid;
formatid = toId(formatid);
// this should relieve login server strain
// this.mmrCache[formatid] = 1000;
if (this.mmrCache[formatid]) {
callback(this.mmrCache[formatid]);
return;
}
LoginServer.request('mmr', {
format: formatid,
user: userid
}, function (data, statusCode, error) {
var mmr = 1000;
error = (error || true);
if (data) {
if (data.errorip) {
self.popup("This server's request IP " + data.errorip + " is not a registered server.");
return;
}
mmr = parseInt(data, 10);
if (!isNaN(mmr) && self.userid === userid) {
error = false;
self.mmrCache[formatid] = mmr;
} else {
mmr = 1000;
}
}
callback(mmr, error);
});
};
User.prototype.cacheMMR = function (formatid, mmr) {
if (typeof mmr === 'number') {
this.mmrCache[formatid] = mmr;
} else {
this.mmrCache[formatid] = Number(mmr.acre);
}
};
User.prototype.mute = function (roomid, time, force, noRecurse) {
if (!roomid) roomid = 'lobby';
if (this.mutedRooms[roomid] && !force) return;
if (!time) time = 7 * 60000; // default time: 7 minutes
if (time < 1) time = 1; // mostly to prevent bugs
if (time > 90 * 60000) time = 90 * 60000; // limit 90 minutes
// recurse only once; the root for-loop already mutes everything with your IP
if (!noRecurse) {
for (var i in users) {
if (users[i] === this || users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].mute(roomid, time, force, true);
break;
}
}
}
}
var self = this;
if (this.mutedRooms[roomid]) clearTimeout(this.mutedRooms[roomid]);
this.mutedRooms[roomid] = setTimeout(function () {
self.unmute(roomid, true);
}, time);
this.muteDuration[roomid] = time;
this.updateIdentity(roomid);
};
User.prototype.unmute = function (roomid, expired) {
if (!roomid) roomid = 'lobby';
if (this.mutedRooms[roomid]) {
clearTimeout(this.mutedRooms[roomid]);
delete this.mutedRooms[roomid];
if (expired) this.popup("Your mute has expired.");
this.updateIdentity(roomid);
}
};
User.prototype.ban = function (noRecurse, userid) {
// recurse only once; the root for-loop already bans everything with your IP
if (!userid) userid = this.userid;
if (!noRecurse) {
for (var i in users) {
if (users[i] === this || users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].ban(true, userid);
break;
}
}
}
}
for (var ip in this.ips) {
bannedIps[ip] = userid;
}
if (this.autoconfirmed) bannedUsers[this.autoconfirmed] = userid;
if (this.registered) {
bannedUsers[this.userid] = userid;
this.locked = userid; // in case of merging into a recently banned account
this.autoconfirmed = '';
}
this.disconnectAll();
};
User.prototype.lock = function (noRecurse, userid) {
// recurse only once; the root for-loop already locks everything with your IP
if (!userid) userid = this.userid;
if (!noRecurse) {
for (var i in users) {
if (users[i] === this || users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].lock(true, userid);
break;
}
}
}
}
for (var ip in this.ips) {
lockedIps[ip] = userid;
}
if (this.autoconfirmed) lockedUsers[this.autoconfirmed] = userid;
if (this.registered) lockedUsers[this.userid] = userid;
this.locked = userid;
this.autoconfirmed = '';
this.updateIdentity();
};
User.prototype.joinRoom = function (room, connection) {
room = Rooms.get(room);
if (!room) return false;
if (!this.can('bypassall')) {
// check if user has permission to join
if (room.staffRoom && !this.isStaff) return false;
if (room.checkBanned && !room.checkBanned(this)) {
return null;
}
}
if (!connection) {
for (var i = 0; i < this.connections.length; i++) {
// only join full clients, not pop-out single-room
// clients
if (this.connections[i].rooms['global']) {
this.joinRoom(room, this.connections[i]);
}
}
return true;
}
if (!connection.rooms[room.id]) {
connection.joinRoom(room);
if (!this.roomCount[room.id]) {
this.roomCount[room.id] = 1;
room.onJoin(this, connection);
} else {
this.roomCount[room.id]++;
room.onJoinConnection(this, connection);
}
}
return true;
};
User.prototype.leaveRoom = function (room, connection, force) {
room = Rooms.get(room);
if (room.id === 'global' && !force) {
// you can't leave the global room except while disconnecting
return false;
}
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection || !connection) {
if (this.connections[i].rooms[room.id]) {
if (this.roomCount[room.id]) {
this.roomCount[room.id]--;
if (!this.roomCount[room.id]) {
room.onLeave(this);
delete this.roomCount[room.id];
}
}
if (!this.connections[i]) {
// race condition? This should never happen, but it does.
fs.createWriteStream('logs/errors.txt', {'flags': 'a'}).on("open", function (fd) {
this.write("\nconnections = " + JSON.stringify(this.connections) + "\ni = " + i + "\n\n");
this.end();
});
} else {
this.connections[i].sendTo(room.id, '|deinit');
this.connections[i].leaveRoom(room);
}
}
if (connection) {
break;
}
}
}
if (!connection && this.roomCount[room.id]) {
room.onLeave(this);
delete this.roomCount[room.id];
}
};
User.prototype.prepBattle = function (formatid, type, connection, callback) {
// all validation for a battle goes through here
if (!connection) connection = this;
if (!type) type = 'challenge';
if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') {
var message = "The server is shutting down. Battles cannot be started at this time.";
if (Rooms.global.lockdown === 'ddos') {
message = "The server is under attack. Battles cannot be started at this time.";
}
connection.popup(message);
setImmediate(callback.bind(null, false));
return;
}
if (ResourceMonitor.countPrepBattle(connection.ip || connection.latestIp, this.name)) {
connection.popup("Due to high load, you are limited to 6 battles every 3 minutes.");
setImmediate(callback.bind(null, false));
return;
}
var format = Tools.getFormat(formatid);
if (!format['' + type + 'Show']) {
connection.popup("That format is not available.");
setImmediate(callback.bind(null, false));
return;
}
TeamValidator.validateTeam(formatid, this.team, this.finishPrepBattle.bind(this, connection, callback));
};
User.prototype.finishPrepBattle = function (connection, callback, success, details) {
if (!success) {
connection.popup("Your team was rejected for the following reasons:\n\n- " + details.replace(/\n/g, '\n- '));
callback(false);
} else {
if (details) {
this.team = details;
ResourceMonitor.teamValidatorChanged++;
} else {
ResourceMonitor.teamValidatorUnchanged++;
}
callback(true);
}
};
User.prototype.updateChallenges = function () {
var challengeTo = this.challengeTo;
if (challengeTo) {
challengeTo = {
to: challengeTo.to,
format: challengeTo.format
};
}
this.send('|updatechallenges|' + JSON.stringify({
challengesFrom: Object.map(this.challengesFrom, 'format'),
challengeTo: challengeTo
}));
};
User.prototype.makeChallenge = function (user, format/*, isPrivate*/) {
user = getUser(user);
if (!user || this.challengeTo) {
return false;
}
if (user.blockChallenges && !this.can('bypassblocks', user)) {
return false;
}
if (new Date().getTime() < this.lastChallenge + 10000) {
// 10 seconds ago
return false;
}
var time = new Date().getTime();
var challenge = {
time: time,
from: this.userid,
to: user.userid,
format: '' + (format || ''),
//isPrivate: !!isPrivate, // currently unused
team: this.team
};
this.lastChallenge = time;
this.challengeTo = challenge;
user.challengesFrom[this.userid] = challenge;
this.updateChallenges();
user.updateChallenges();
};
User.prototype.cancelChallengeTo = function () {
if (!this.challengeTo) return true;
var user = getUser(this.challengeTo.to);
if (user) delete user.challengesFrom[this.userid];
this.challengeTo = null;
this.updateChallenges();
if (user) user.updateChallenges();
};
User.prototype.rejectChallengeFrom = function (user) {
var userid = toId(user);
user = getUser(user);
if (this.challengesFrom[userid]) {
delete this.challengesFrom[userid];
}
if (user) {
delete this.challengesFrom[user.userid];
if (user.challengeTo && user.challengeTo.to === this.userid) {
user.challengeTo = null;
user.updateChallenges();
}
}
this.updateChallenges();
};
User.prototype.acceptChallengeFrom = function (user) {
var userid = toId(user);
user = getUser(user);
if (!user || !user.challengeTo || user.challengeTo.to !== this.userid || !this.connected || !user.connected) {
if (this.challengesFrom[userid]) {
delete this.challengesFrom[userid];
this.updateChallenges();
}
return false;
}
Rooms.global.startBattle(this, user, user.challengeTo.format, this.team, user.challengeTo.team, {rated: false});
delete this.challengesFrom[user.userid];
user.challengeTo = null;
this.updateChallenges();
user.updateChallenges();
return true;
};
// chatQueue should be an array, but you know about mutables in prototypes...
// P.S. don't replace this with an array unless you know what mutables in prototypes do.
User.prototype.chatQueue = null;
User.prototype.chatQueueTimeout = null;
User.prototype.lastChatMessage = 0;
/**
* The user says message in room.
* Returns false if the rest of the user's messages should be discarded.
*/
User.prototype.chat = function (message, room, connection) {
var now = new Date().getTime();
if (message.substr(0, 16) === '/cmd userdetails') {
// certain commands are exempt from the queue
ResourceMonitor.activeIp = connection.ip;
room.chat(this, message, connection);
ResourceMonitor.activeIp = null;
return false; // but end the loop here
}
if (this.chatQueueTimeout) {
if (!this.chatQueue) this.chatQueue = []; // this should never happen
if (this.chatQueue.length >= THROTTLE_BUFFER_LIMIT - 1) {
connection.sendTo(room, '|raw|' +
"<strong class=\"message-throttle-notice\">Your message was not sent because you've been typing too quickly.</strong>"
);
return false;
} else {
this.chatQueue.push([message, room, connection]);
}
} else if (now < this.lastChatMessage + THROTTLE_DELAY) {
this.chatQueue = [[message, room, connection]];
this.chatQueueTimeout = setTimeout(
this.processChatQueue.bind(this),
THROTTLE_DELAY - (now - this.lastChatMessage));
} else {
this.lastChatMessage = now;
ResourceMonitor.activeIp = connection.ip;
room.chat(this, message, connection);
ResourceMonitor.activeIp = null;
}
};
User.prototype.clearChatQueue = function () {
this.chatQueue = null;
if (this.chatQueueTimeout) {
clearTimeout(this.chatQueueTimeout);
this.chatQueueTimeout = null;
}
};
User.prototype.processChatQueue = function () {
if (!this.chatQueue) return; // this should never happen
var toChat = this.chatQueue.shift();
ResourceMonitor.activeIp = toChat[2].ip;
toChat[1].chat(this, toChat[0], toChat[2]);
ResourceMonitor.activeIp = null;
if (this.chatQueue && this.chatQueue.length) {
this.chatQueueTimeout = setTimeout(
this.processChatQueue.bind(this), THROTTLE_DELAY);
} else {
this.chatQueue = null;
this.chatQueueTimeout = null;
}
};
User.prototype.destroy = function () {
// deallocate user
for (var roomid in this.mutedRooms) {
clearTimeout(this.mutedRooms[roomid]);
delete this.mutedRooms[roomid];
}
this.clearChatQueue();
delete users[this.userid];
};
User.prototype.toString = function () {
return this.userid;
};
// "static" function
User.pruneInactive = function (threshold) {
var now = Date.now();
for (var i in users) {
var user = users[i];
if (user.connected) continue;
if ((now - user.lastConnected) > threshold) {
users[i].destroy();
}
}
};
return User;
})();
Connection = (function () {
function Connection(id, worker, socketid, user, ip) {
this.id = id;
this.socketid = socketid;
this.worker = worker;
this.rooms = {};
this.user = user;
this.ip = ip || '';
}
Connection.prototype.sendTo = function (roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
Sockets.socketSend(this.worker, this.socketid, data);
ResourceMonitor.countNetworkUse(data.length);
};
Connection.prototype.send = function (data) {
Sockets.socketSend(this.worker, this.socketid, data);
ResourceMonitor.countNetworkUse(data.length);
};
Connection.prototype.destroy = function () {
Sockets.socketDisconnect(this.worker, this.socketid);
this.onDisconnect();
};
Connection.prototype.onDisconnect = function () {
delete connections[this.id];
if (this.user) this.user.onDisconnect(this);
this.user = null;
};
Connection.prototype.popup = function (message) {
this.send('|popup|' + message.replace(/\n/g, '||'));
};
Connection.prototype.joinRoom = function (room) {
if (room.id in this.rooms) return;
this.rooms[room.id] = room;
Sockets.channelAdd(this.worker, room.id, this.socketid);
};
Connection.prototype.leaveRoom = function (room) {
if (room.id in this.rooms) {
delete this.rooms[room.id];
Sockets.channelRemove(this.worker, room.id, this.socketid);
}
};
return Connection;
})();
Users.User = User;
Users.Connection = Connection;
/*********************************************************
* Inactive user pruning
*********************************************************/
Users.pruneInactive = User.pruneInactive;
Users.pruneInactiveTimer = setInterval(
User.pruneInactive,
1000 * 60 * 30,
Config.inactiveuserthreshold || 1000 * 60 * 60
);
|
Ransei1/Alt
|
users.js
|
JavaScript
|
mit
| 54,422 |
import React from 'react';
import expect from 'expect';
import sinon from 'sinon';
import {mount,shallow} from 'enzyme';
import * as DocActions from '../../../actions/DocumentActions';
import DocStore from '../../../stores/DocumentStore';
import Updater from '../Updater.jsx';
describe('Document Update Component Tests', function() {
describe('Component Rendering Tests', function() {
var component;
beforeEach(() => {
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
}
component = shallow(<Updater doc={data} />);
});
it('renders the component correctly', function() {
expect(component.hasClass('row')).toBe(true);
expect(component.find('.input-field').length).toEqual(2);
expect(component.find('textarea').length).toEqual(1);
component.unmount();
});
it('initializes with the correct state', function() {
expect(component.state().doc.accessLevel).toBe('private');
expect(component.state().doc.content).toBe('Doc to be updated');
expect(component.state().doc.title).toBe('Test');
component.unmount();
});
});
describe('Component LifeCycle Tests', function() {
var component;
beforeEach(() => {
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
};
window.Materialize.toast = sinon.spy();
component = mount(<Updater doc={data} />);
});
it('Calls componentWillMount', function() {
sinon.spy(Updater.prototype, 'componentWillMount');
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
};
sinon.spy(DocStore, 'addChangeListener');
component = mount(<Updater doc={data} />);
expect(Updater.prototype.componentWillMount.called).toBe(true);
expect(DocStore.addChangeListener.called).toBe(true);
Updater.prototype.componentWillMount.restore();
DocStore.addChangeListener.restore();
component.unmount();
});
it('Calls componentWillUnmount', function() {
sinon.spy(Updater.prototype, 'componentWillUnmount');
sinon.spy(DocStore, 'removeChangeListener');
component.unmount();
expect(Updater.prototype.componentWillUnmount.called).toBe(true);
expect(DocStore.removeChangeListener.called).toBe(true);
Updater.prototype.componentWillUnmount.restore();
DocStore.removeChangeListener.restore();
});
});
describe('Component Method Tests', function() {
window.Materialize = {};
var component;
beforeEach(() => {
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
}
window.Materialize.toast = sinon.spy();
component = mount(<Updater doc={data} />);
});
afterEach(function() {
component.unmount();
});
it('handleDocUpdate no error', function() {
sinon.stub(DocActions, 'getUserDocs').returns({});
let instance = component.instance();
let data = {
doc: {
title: 'Test title',
content: 'edwin',
accessLevel: 'private'
},
message: 'Update success '
};
DocStore.setDocUpdateResult(data);
sinon.spy(instance, 'handleDocUpdate');
sinon.spy(DocStore, 'getDocUpdateResult');
sinon.spy(localStorage, 'getItem');
instance.handleDocUpdate();
expect(DocStore.getDocUpdateResult.called).toBe(true);
expect(window.Materialize.toast.withArgs(data.message).called).toBe(true);
expect(localStorage.getItem.withArgs('token').called).toBe(true);
instance.handleDocUpdate.restore();
DocStore.getDocUpdateResult.restore();
DocActions.getUserDocs.restore();
localStorage.getItem.restore();
});
it('handleDocUpdate error handling', function() {
sinon.stub(DocActions, 'getUserDocs').returns({});
let instance = component.instance();
let data = {
error: {
message: 'update error'
}
};
DocStore.setDocUpdateResult(data);
sinon.spy(instance, 'handleDocUpdate');
sinon.spy(DocStore, 'getDocUpdateResult');
instance.handleDocUpdate();
expect(DocStore.getDocUpdateResult.called).toBe(true);
expect(window.Materialize.toast.withArgs(data.error.message).called).toBe(true);
instance.handleDocUpdate.restore();
DocStore.getDocUpdateResult.restore();
DocActions.getUserDocs.restore();
});
it('should call handleSubmit with update data', function() {
sinon.stub(DocActions, 'updateDoc').returns({});
let instance = component.instance();
component.setState({
doc: {
title: 'Update Test',
content: 'This is a test doc',
accessLevel: 'public'
}
});
// simulate the Update event
let updateEvent = {
preventDefault: function() {}
};
sinon.spy(instance, 'handleSubmit');
sinon.spy(updateEvent, 'preventDefault');
component.find('form').simulate('submit', updateEvent);
expect(updateEvent.preventDefault.called).toBe(true);
expect(DocActions.updateDoc.called).toBe(true);
DocActions.updateDoc.restore();
});
it('should correctly update the state', function() {
let fieldChangeEvent = {
target: {
name: 'title',
value: 'Test Document'
},
preventDefault: function() {}
};
const instance = component.instance();
sinon.spy(instance, 'handleFieldChange');
instance.handleFieldChange(fieldChangeEvent);
expect(component.state().doc[fieldChangeEvent.target.name]).toBe(fieldChangeEvent.target.value);
instance.handleFieldChange.restore();
});
});
});
|
andela-ekupara/DcManFrontEnd
|
app/scripts/components/DocsManagement/__tests__/Updater-test.js
|
JavaScript
|
mit
| 5,833 |
export { default, initialize } from 'ember-intl-phraseapp/instance-initializers/ember-intl-phraseapp';
|
alienspaces/ember-intl-phraseapp
|
app/instance-initializers/ember-intl-phraseapp.js
|
JavaScript
|
mit
| 102 |
import {combineReducers} from 'redux';
import {routerReducer as routing} from 'react-router-redux';
import {reducer as form} from 'redux-form';
import {reducer as socket} from 'redux-sockets';
import auth from './reducers/auth';
import home from './App/Shell/Home/redux';
import login from './App/Exterior/Login/redux';
export default combineReducers({
routing,
form,
auth,
home,
socket,
login
});
|
noamokman/project-starter-sample
|
client/reducer.js
|
JavaScript
|
mit
| 410 |
System.register(['angular2/platform/browser', './todo', 'angular2/http'], function(exports_1) {
var browser_1, todo_1, http_1;
return {
setters:[
function (browser_1_1) {
browser_1 = browser_1_1;
},
function (todo_1_1) {
todo_1 = todo_1_1;
},
function (http_1_1) {
http_1 = http_1_1;
}],
execute: function() {
browser_1.bootstrap(todo_1.TodoAppComponent, [http_1.HTTP_BINDINGS]);
}
}
});
//# sourceMappingURL=index.js.map
|
thomasgzh/MEAN-ts-ng2-appframework
|
public/controllers/index.js
|
JavaScript
|
mit
| 607 |
import React from 'react'
import Overdrive from 'react-overdrive'
const img = 'http://coalcreekapparel.com/wp-content/uploads/2015/05/ty1.png'
export default () => (
<div className="jayhawks">
<Overdrive id="element" style={{ display: 'inline-block' }}>
<img src={img} width="50%" alt="jayhawks" />
</Overdrive>
</div>
)
|
RCWS-Development/deploying-with-now
|
otherDeployments/cra-app/src/components/Jayhawks.js
|
JavaScript
|
mit
| 341 |
let userArray = process.argv.slice(2);
let data = {};
[, data.username, data.email] = userArray;
console.log(data);
|
Badacadabra/hello-js-world
|
nodeschool/count-to-6/destructuring.js
|
JavaScript
|
mit
| 117 |
var express = require('express');
var router = express.Router();
// www.example.com/todos/
router.get('/',function(req,res,next){
res.json({"message" : "Hello, this is the todo message."});
});
module.exports = router;
|
hardiskbohra/First-Database-Demo
|
routes/todos.js
|
JavaScript
|
mit
| 223 |
import Flickr from "@/flickr"
export default function checkToken({ flickr = Flickr, authToken = `` } = {}) {
return flickr.fetchResource(`flickr.auth.checkToken`, { authToken })
}
|
Saeris/Flickr-Wormhole
|
src/methods/auth/checkToken.js
|
JavaScript
|
mit
| 183 |
Ext.define('sisprod.view.VerifyActsOrConditions.UpdateVerifyActsOrConditions', {
extend: 'sisprod.view.base.BaseDataWindow',
alias: 'widget.updateVerifyActsOrConditions',
require: [
'sisprod.view.base.BaseDataWindow',
'sisprod.view.base.SensitiveComboBox'
],
messages: {
validation: {
alertTitle: 'Message',
firstSelectWorkCategoryText: 'Please, first select work category...'
},
formTitle: 'Request Data',
lotLabel: 'Lot',
requestDateLabel: 'Date',
workCategoryLabel: 'Work Category',
workCategoryDetailLabel: 'Work Type',
workCategoryDetailEmptyText: 'Type work type name',
workCategoryEmptyText: 'Type work category',
workRequestSourceLabel: 'Work Request Source',
workRequestFullNumberLabel: 'Request Number',
equipmentTypeLabel: 'Equipment Type',
equipmentLabel: 'Equipment',
equipmentEmptyText: 'Type an equipment name...',
locationLabel: 'Location',
locationEmptyText: 'Type a location name',
applicantLabel: 'Applicant',
applicantEmptyText: 'Type an employee name',
recipientLabel: 'Recipient',
recipientEmptyText: 'Type an employee name',
workDetailsLabel: 'Type work detail to perform',
firstSelectAlertText: 'Select equipment type before perform search!',
firstSelectWorkCategoryAlertText: 'Select work category before perform search!',
isSubstandardConditionLabel: 'Condition SubStandard',
detectionDateLabel: 'Detencion Date',
subStandardLabel: 'SubStandard',
subStandardConditionActionLabel: 'SubStandard Condition Action',
hsseSupervisorLabel: 'Supervisor',
hsseSupervisorEmptyText: 'Hsse Supervisor',
subStandardTitle: 'SubStandard',
observationsLabel: 'Observations'
},
title: 'Update Work Request',
modal: true,
width: 660,
layout: 'fit',
initComponent: function() {
var me = this;
me.formOptions = {
region: 'center',
bodyStyle: 'padding:5px 5px 0',
items: [
{
xtype: 'hiddenfield',
name: 'idWorkRequest',
id: 'idWorkRequest'
},
{
xtype: 'fieldset',
title: me.messages.formTitle,
defaultType: 'textfield',
defaults: {anchor: '100%', labelWidth: 120},
layout: 'anchor',
items: [
{
xtype: 'textfield',
name: 'workRequestFullNumber',
id: 'workRequestFullNumber',
anchor: '45%',
fieldLabel: me.messages.workRequestFullNumberLabel,
labelWidth: 120,
readOnly: true
},
{
xtype: 'fieldcontainer',
layout: 'hbox',
anchor: '100%',
items: [
{
xtype: 'combofieldcontainer',
flex: 5,
showButtons: false,
comboBoxOptions: {
readOnly: true,
name: 'idLot',
id: 'idLot',
labelWidth: 120,
store: Ext.create('sisprod.store.LotAll', {autoLoad: true}),
fieldLabel: me.messages.lotLabel,
displayField: 'lotName',
valueField: 'idLot',
emptyText: 'Seleccione',
forceSelection: true,
allowBlank: false
}
},
{
xtype: 'datefield',
name: 'requestDate',
fieldLabel: me.messages.requestDateLabel,
flex: 2,
value: new Date(),
readOnly: true
}
]
},
{
xtype: 'combofieldcontainer',
showButtons: false,
comboBoxOptions: {
name: 'idWorkRequestSource',
id: 'idWorkRequestSource',
store: Ext.create('sisprod.store.WorkRequestSourceAll', {autoLoad: true}),
fieldLabel: me.messages.workRequestSourceLabel,
labelWidth: 120,
displayField: 'workRequestSourceName',
valueField: 'idWorkRequestSource',
emptyText: 'Seleccione',
forceSelection: true,
allowBlank: false,
readOnly: true,
width: 400
}
},
{
xtype: 'sensitivecombocontainer',
anchor: '80%',
showAddButton: false,
sensitiveComboBoxOptions: {
hideTrigger: false,
readOnly: true,
name: 'idWorkCategory',
id: 'idWorkCategory',
labelWidth: 120,
store: Ext.create('sisprod.store.WorkCategoryByNameStore'),
fieldLabel: me.messages.workCategoryLabel,
emptyText: me.messages.workCategoryEmptyText,
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{workCategoryName}', '</tpl>'),
valueField: 'idWorkCategory',
listConfig: {
getInnerTpl: function() {
return "{workCategoryName}";
}
},
forceSelection: true,
allowBlank: false
}
},
{
xtype: 'sensitivecombocontainer',
anchor: '80%',
showAddButton: false,
sensitiveComboBoxOptions: {
hideTrigger: false,
readOnly: true,
name: 'idWorkCategoryDetail',
id: 'idWorkCategoryDetail',
fieldLabel: me.messages.workCategoryDetailLabel,
labelWidth: 120,
store: Ext.create('sisprod.store.WorkCategoryDetailByCategory', {
listeners: {
beforeload: function(store, operation, options) {
var idWorkCategory = me.down('#idWorkCategory').getValue();
if (Ext.isDefined(idWorkCategory) && idWorkCategory !== null) {
if (Ext.isDefined(operation.params) && operation.params !== null)
operation.params.idWorkCategory = idWorkCategory;
else
operation.params = {query: '', idWorkCategory: idWorkCategory};
}
else {
Ext.Msg.alert(me.messages.validation.alertTitle, me.messages.validation.firstSelectWorkCategoryText);
return false;
}
}
}
}),
emptyText: me.messages.workCategoryDetailEmptyText,
forceSelection: true,
allowBlank: false,
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{workCategoryDetailName}', '</tpl>'),
valueField: 'idWorkCategoryDetail',
listConfig: {
getInnerTpl: function() {
return "{workCategoryDetailName}";
}
}
}
},
{
xtype: 'combobox',
anchor: '50%',
fieldLabel: me.messages.equipmentTypeLabel,
labelWidth: 120,
store: Ext.create('sisprod.store.EquipmentTypeAll', {autoLoad: true}),
displayField: 'equipmentTypeName',
valueField: 'idEquipmentType',
name: 'idSelectEquipmentType',
id: 'idSelectEquipmentType',
emptyText: 'Seleccione',
allowBlank: false,
readOnly: true,
showAddButton: false,
forceSelection: true
},
{
xtype: 'sensitivecombocontainer',
anchor: '80%',
showAddButton: false,
sensitiveComboBoxOptions: {
name: 'idEquipment',
id: 'idEquipment',
fieldLabel: me.messages.equipmentLabel,
labelWidth: 120,
readOnly: true,
store: Ext.create('sisprod.store.EquipmentAllByType', {
// autoLoad: true,
listeners: {
beforeload: function(store, operation, options) {
var form = me.down('form');
var equipmentTypeInput = form.queryById('idSelectEquipmentType');
var selectedEquipmentType = equipmentTypeInput.getValue();
if (Ext.isDefined(selectedEquipmentType) && selectedEquipmentType !== null)
operation.params.idEquipmenType = selectedEquipmentType;
else {
Ext.Msg.alert(me.messages.formTitle, me.messages.firstSelectAlertText);
return false;
}
}
}
}),
emptyText: me.messages.equipmentEmptyText,
forceSelection: true,
hideTrigger: false,
allowBlank: false,
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{equipmentName} ({locationName})', '</tpl>'),
valueField: 'idEquipment',
listConfig: {
getInnerTpl: function() {
return "{equipmentName} ({locationName})";
}
}
}
},
{
xtype: 'sensitivecombocontainer',
showAddButton: false,
anchor: '80%',
sensitiveComboBoxOptions: {
name: 'idApplicant',
fieldLabel: me.messages.applicantLabel,
labelWidth: 120,
store: Ext.create('sisprod.store.EmployeeFromGMP'),
emptyText: me.messages.applicantEmptyText,
id: 'idApplicant',
forceSelection: true,
hideTrigger: false,
readOnly: true,
allowBlank: false,
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{personFullName} ({fullDocumentNumber})', '</tpl>'),
valueField: 'idEmployee',
listConfig: {
getInnerTpl: function() {
return '{personFullName} ({fullDocumentNumber})';
}
}
}
},
{
xtype: 'checkbox',
name: 'isSubstandardCondition',
id: 'isSubstandardCondition',
anchor: '50%',
// fieldLabel: 'is Substandard Condition',
labelWidth: '50%',
fieldLabel: me.messages.isSubstandardConditionLabel,
inputValue: true
}
]
},
{
xtype: 'fieldset',
title: me.messages.subStandardTitle,
layout: 'anchor',
id: 'ipPanelSubstandard',
hidden: true,
bodyPadding: 2,
items: [
// {
// xtype: 'sensitivecombocontainer',
// showAddButton: false,
// anchor: '100%',
// hidden: true,
// sensitiveComboBoxOptions: {
// name: 'idHsseSupervisor',
// hideTrigger: false,
// labelWidth: 100,
// fieldLabel: me.messages.hsseSupervisorLabel,
// store: Ext.create('sisprod.store.HsseSupervisorTemplate'),
// emptyText: me.messages.applicantEmptyText,
// id: 'idHsseSupervisor',
// value: 0,
// forceSelection: true,
// displayTpl: Ext.create('Ext.XTemplate',
// '<tpl for=".">', '{personFullName} ({fullDocumentNumber})', '</tpl>'),
// valueField: 'idHsseSupervisor',
// listConfig: {
// getInnerTpl: function() {
// return '{personFullName} ({fullDocumentNumber})';
// }
// }
// }
//
// },
{
xtype: 'fieldcontainer',
anchor: '100%',
layout: {
type: 'hbox',
padding: '0 0 0 0'
},
items: [
{
xtype: 'combobox',
anchor: '50%',
margin: '0 0 0 10',
flex: 1,
labelWidth: 100,
id: 'idSubstandard',
fieldLabel: me.messages.subStandardLabel,
store: Ext.create('sisprod.store.SubstandardAll').load(),
displayField: 'substandardName',
valueField: 'idSubstandard',
name: 'idSubstandard',
emptyText: ' ',
forceSelection: true,
editable: false
},
{
xtype: 'datefield',
name: 'detectionDate',
id: 'detectionDate',
margin: '0 0 0 10',
labelWidth: 100,
anchor: '50%',
maxValue: me.record.raw.requestDate,
fieldLabel: me.messages.detectionDateLabel
}
]
},
{
xtype: 'sensitivecombo',
anchor: '100%',
name: 'idSubstandardConditionAction',
hideTrigger: false,
labelWidth: 100,
fieldLabel: me.messages.subStandardConditionActionLabel,
store: Ext.create('sisprod.store.SubstandardConditionActionAutocomplete'),
id: 'idSubstandardConditionAction',
emptyText: '',
valueField: 'idSubstandardConditionAction',
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{description}', '</tpl>'),
listConfig: {
getInnerTpl: function() {
return '{description}';
}
}
},
{
xtype: 'textareafield',
name: 'observations',
id: 'observations',
maxLength: 5000,
allowBlank: true,
labelWidth: 100,
anchor: '100%',
fieldLabel: me.messages.observationsLabel
}
]
},
{
xtype: 'fieldset',
columnWidth: 0.5,
title: me.messages.workDetailsLabel,
defaultType: 'textfield',
defaults: {anchor: '100%'},
layout: 'anchor',
items: [
{
xtype: 'textareafield',
anchor: '100%',
name: 'description',
id: 'description',
maxLength: 5000,
readOnly: true,
allowBlank: false
}
]
}
]
};
me.callParent(arguments);
}
});
|
jgin/testphp
|
web/bundles/hrmpayroll/app/view/VerifyActsOrConditions/UpdateVerifyActsOrConditions.js
|
JavaScript
|
mit
| 21,362 |
var myApp = new Framework7({
// Default title for modals
modalTitle: 'My App',
// If it is webapp, we can enable hash navigation:
pushState: true,
// Hide and show indicator during ajax requests
onAjaxStart: function (xhr) {
myApp.showIndicator();
},
onAjaxComplete: function (xhr) {
myApp.hideIndicator();
}
});
|
TekTicks/socialworker
|
test/path/to/my-app.js
|
JavaScript
|
mit
| 371 |
/*
* Star Wars opening crawl from 1977
*
* I freaking love Star Wars, but could not find
* a web version of the original opening crawl from 1977.
* So I created this one.
*
* I wrote an article where I explain how this works:
* http://timpietrusky.com/star-wars-opening-crawl-from-1977
*
* Watch the Start Wars opening crawl on YouTube.
* https://www.youtube.com/watch?v=7jK-jZo6xjY
*
* Stuff I used:
* - CSS (animation, transform)
* - HTML audio (the opening theme)
* - SVG (the Star Wars logo from wikimedia.org)
* http://commons.wikimedia.org/wiki/File:Star_Wars_Logo.svg
* - JavaScript (to sync the animation/audio)
*
* Thanks to Craig Buckler for his amazing article
* which helped me to create this remake of the Star Wars opening crawl.
* http://www.sitepoint.com/css3-starwars-scrolling-text/
*
* Sound copyright by The Walt Disney Company.
*
*
* 2013 by Tim Pietrusky
* timpietrusky.com
*
*/
StarWars = (function() {
/*
* Constructor
*/
function StarWars(args) {
// Context wrapper
this.el = $(args.el);
// Audio to play the opening crawl
this.audio = this.el.find('audio').get(0);
// Start the animation
this.start = this.el.find('.start');
// The animation wrapper
this.animation = this.el.find('.animation');
// Remove animation and shows the start screen
this.reset();
// Start the animation on click
this.start.bind('click', $.proxy(function() {
this.start.hide();
this.audio.play();
this.el.append(this.animation);
}, this));
// Reset the animation and shows the start screen
$(this.audio).bind('ended', $.proxy(function() {
this.audio.currentTime = 0;
window.location.href = "main.html";
}, this));
}
/*
* Resets the animation and shows the start screen.
*/
StarWars.prototype.reset = function() {
this.start.show();
this.cloned = this.animation.clone(true);
this.animation.remove();
this.animation = this.cloned;
};
return StarWars;
})();
new StarWars({
el : '.starwars'
});
|
brunorafaeli/brunorafaeli.github.io
|
cg/js/starwars.js
|
JavaScript
|
mit
| 2,104 |
// getAllAuthors(layout_callback, fail_callback)
//
// layout_callback = function(list_of_authors)
// fail_callback = function()
//
// Will get all Authors currently in the system, passing the whole list
// to the provided layout_callback function.
//
var getAllAuthors = function() {
};
$(document).ready(function() {
getAllAuthors = function(layout_callback, fail_callback) {
$.getJSON("${project.web.contextPath}/author/getAll.ajax")
.done(function(data) {
layout_callback(data.content);
}).fail(function() {
fail_callback();
});
}
});
|
snowjak88/charcraft
|
charcraft/src/main/webapp/javascript/authorAjax.js
|
JavaScript
|
mit
| 596 |
angular.module('app')
.controller('UserSettingsController', function ($scope, $rootScope) {
});
|
FridgeTeam/Fridge
|
Fridge/Fridge.WebClient/controllers/user/UserSettingsController.js
|
JavaScript
|
mit
| 105 |
var config = {}
config.debug = true;
config.port = 8000;
module.exports = config;
|
gbleu/newrelic-xfd
|
config.js
|
JavaScript
|
mit
| 87 |
'use strict';
// User routes use users controller
var users = require('../controllers/users');
var authorization = require('./middlewares/authorization');
module.exports = function(app, passport) {
app.get('/logout', users.signout);
app.get('/api/users', authorization.requiresAdmin, users.all);
app.get('/api/users/me', users.me);
// Setting up the users api
app.post('/register', users.create);
// AngularJS route to check for authentication
app.get('/loggedin', function(req, res) {
res.json(200, req.isAuthenticated() ? {user: {name: req.user.name, roles: req.user.roles}} : {user: null});
});
// Setting the local strategy route
app.post('/login', passport.authenticate('local', {
failureFlash: true
}), function (req, res) {
req.session.locale = req.user.locale;
res.send({user: {name: req.user.name, roles: req.user.roles}});
});
};
|
Azema/phigratejs
|
server/routes/users.js
|
JavaScript
|
mit
| 886 |
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z' })
);
};
|
goto-bus-stop/deku-material-svg-icons
|
lib/action/build.js
|
JavaScript
|
mit
| 467 |
var React = require('react');
var pathToRegexp = require('path-to-regexp');
var assign = require('object-assign');
var zipObject = require('lodash/array/zipObject');
var clone = require('lodash/lang/clone');
var pluck = require('lodash/collection/pluck');
var DOM = React.DOM;
var createClass = React.createClass;
var PropTypes = React.PropTypes;
var Children = React.Children;
var cloneElement = React.cloneElement;
var Routsy = {
// Private, singleton store for all routes
// TODO: add scope to props of route element?
routes: [],
listeners: [],
navigateTo: function (path) {
window.location.hash = path;
},
currentPath: function () {
var rawPath = window.location.hash.split('#')[1];
if (rawPath === undefined) {
rawPath = '/';
}
return rawPath;
},
currentPathMatches: function (path) {
return path === Routsy.currentPath();
},
// TODO: test this
removeHash: function () {
history.pushState(
'',
document.title,
window.location.pathname + window.location.search
);
}
};
// No need to remove this event listener. It needs
// to live as long as the app does
window.addEventListener('hashchange', function () {
Routsy.listeners.forEach(function (fn) {
fn();
});
});
function onHashChange (fn) {
Routsy.listeners.push(fn);
}
Routsy.Link = createClass({
propTypes: {
path: PropTypes.string.isRequired,
activeClassName: PropTypes.string,
activeStyle: PropTypes.object
},
getDefaultProps: function () {
return {
activeClassName: 'active',
activeStyle: {}
};
},
getInitialState: function () {
return {
active: false
};
},
componentDidMount: function () {
this.setActiveClassName();
onHashChange(this.hashChanged);
},
hashChanged: function () {
this.setActiveClassName();
},
setActiveClassName: function () {
this.setState({
active: Routsy.currentPathMatches(this.props.path)
});
},
gotoPath: function (e) {
e.preventDefault();
Routsy.navigateTo(this.props.path);
this.setActiveClassName();
},
render: function () {
var style = assign(
{
cursor: 'pointer'
},
this.props.style,
this.state.active ? this.props.activeStyle : {}
)
return DOM.a({
style: style,
onClick: this.gotoPath,
className: this.state.active ? this.props.activeClassName : null
}, this.props.children);
}
});
Routsy.Route = createClass({
propTypes: {
path: PropTypes.string.isRequired,
paramsAsProps: PropTypes.object,
willRender: PropTypes.func
},
getDefaultProps: function () {
return {
paramsAsProps: {},
willRender: function () {}
}
},
getInitialState: function () {
return {
path: this.parseHash()
}
},
componentDidMount: function () {
Routsy.routes.push({
path: this.props.path
});
onHashChange(this.hashChange);
},
hashChange: function () {
var path = this.parseHash();
this.setState({path: path});
},
parseHash: function () {
return Routsy.currentPath();
},
shouldRender: function () {
return pathToRegexp(this.props.path).exec(this.parseHash());
},
parseParams: function () {
var pathRegex = pathToRegexp(this.props.path);
var parsedPath = pathToRegexp.parse(this.props.path);
var keys = pluck(parsedPath.slice(1), 'name');
var values = this.parseHash().match(pathRegex).slice(1);
return zipObject(keys, values);
},
render: function () {
var element = null;
var self = this;
if (this.shouldRender()) {
var params = this.parseParams();
this.props.willRender(params);
// For now, cloning the element and adding the router
// information to the props is the only way to get
// information into the children.
// Hopefully we can change this in the future.
var children = Children.map(this.props.children, function (child) {
if (typeof child === 'string') {
return child;
}
// Map params from paramsAs
var paramsAsProps = {};
Object.keys(self.props.paramsAsProps)
.forEach(function (key) {
var mapToKey = self.props.paramsAsProps[key]
paramsAsProps[mapToKey] = params[key];
});
var props = assign(clone(child.props), {
router: {
params: params
}
}, paramsAsProps);
return cloneElement(child, props);
});
element = DOM.div(null, children);
}
return element;
}
});
module.exports = Routsy;
|
laurelandwolf/react-routsy
|
index.js
|
JavaScript
|
mit
| 4,652 |
'use strict';
module.exports = (request, reply) => {
reply({
app : 'wordist',
currentVersion: 'v1',
versions : [
{
name : 'v1',
status : 'unstable'
}
]
});
};
|
wordist/wordist.xyz
|
pseudo/root.js
|
JavaScript
|
mit
| 208 |
/**
* UserProfile Container
*/
import {connect} from 'react-redux';
import UserProfileRender from './UserProfileView';
/* Redux ==================================================================== */
const mapStateToProps = state => ({
user: state.user
});
// Any actions to map to the component?
const mapDispatchToProps = {
};
export default connect(mapStateToProps, mapDispatchToProps)(UserProfileRender);
|
N3TC4T/Nearby-Live
|
src/containers/main/user-profile/UserProfileContainer.js
|
JavaScript
|
mit
| 419 |
/*
* jsPlumb
*
* Title:jsPlumb 1.3.2
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the jsPlumb core code.
*
* Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://code.google.com/p/jsplumb
*
* Triple licensed under the MIT, GPL2 and Beer licenses.
*/
;(function() {
/**
* Class:jsPlumb
* The jsPlumb engine, registered as a static object in the window. This object contains all of the methods you will use to
* create and maintain Connections and Endpoints.
*/
//var ie = !!!document.createElement('canvas').getContext;
var canvasAvailable = !!document.createElement('canvas').getContext;
var svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
// TODO what is a good test for VML availability? aside from just assuming its there because nothing else is.
var vmlAvailable = !(canvasAvailable | svgAvailable);
var _findIndex = function(a, v, b, s) {
var _eq = function(o1, o2) {
if (o1 === o2)
return true;
else if (typeof o1 == "object" && typeof o2 == "object") {
var same = true;
for ( var propertyName in o1) {
if (!_eq(o1[propertyName], o2[propertyName])) {
same = false;
break;
}
}
for ( var propertyName in o2) {
if (!_eq(o2[propertyName], o1[propertyName])) {
same = false;
break;
}
}
return same;
}
};
for ( var i = +b || 0, l = a.length; i < l; i++) {
if (_eq(a[i], v))
return i;
}
return -1;
};
/**
* helper method to add an item to a list, creating the list if it does
* not yet exist.
*/
var _addToList = function(map, key, value) {
var l = map[key];
if (l == null) {
l = [];
map[key] = l;
}
l.push(value);
return l;
};
var _connectionBeingDragged = null;
var _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); };
var _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); };
var _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); };
var _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); };
var _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); };
var _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); };
var _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); };
var _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); };
var _log = function(jsp, msg) {
if (jsp.logEnabled && typeof console != "undefined")
console.log(msg);
};
/**
* EventGenerator
* Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
*/
var EventGenerator = function() {
var _listeners = {}, self = this;
// this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to
// jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
// listeners to bring down jsPlumb - or do we. i can't make up my mind about this, but i know i want to hear about it if the "ready"
// event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
// to hear what other people think.
var eventsToDieOn = [ "ready" ];
/*
* Binds a listener to an event.
*
* Parameters:
* event - name of the event to bind to.
* listener - function to execute.
*/
this.bind = function(event, listener) {
_addToList(_listeners, event, listener);
};
/*
* Fires an update for the given event.
*
* Parameters:
* event - event to fire
* value - value to pass to the event listener(s).
* o riginalEvent - the original event from the browser
*/
this.fire = function(event, value, originalEvent) {
if (_listeners[event]) {
for ( var i = 0; i < _listeners[event].length; i++) {
// doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
// method will have the whole call stack available in the debugger.
if (_findIndex(eventsToDieOn, event) != -1)
_listeners[event][i](value, originalEvent);
else {
// for events we don't want to die on, catch and log.
try {
_listeners[event][i](value, originalEvent);
} catch (e) {
_log("jsPlumb: fire failed for event " + event + " : " + e);
}
}
}
}
};
/*
* Clears either all listeners, or listeners for some specific event.
*
* Parameters:
* event - optional. constrains the clear to just listeners for this event.
*/
this.clearListeners = function(event) {
if (event) {
delete _listeners[event];
} else {
delete _listeners;
_listeners = {};
}
};
};
/*
* Class:jsPlumbUIComponent
* Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle,
* and also extends EventGenerator to provide the bind and fire methods.
*/
var jsPlumbUIComponent = function(params) {
var self = this, a = arguments, _hover = false;
self._jsPlumb = params["_jsPlumb"];
// all components can generate events
EventGenerator.apply(this);
// all components get this clone function.
// TODO issue 116 showed a problem with this - it seems 'a' that is in
// the clone function's scope is shared by all invocations of it, the classic
// JS closure problem. for now, jsPlumb does a version of this inline where
// it used to call clone. but it would be nice to find some time to look
// further at this.
this.clone = function() {
var o = new Object();
self.constructor.apply(o, a);
return o;
};
this.overlayPlacements = [],
this.paintStyle = null,
this.hoverPaintStyle = null;
// helper method to update the hover style whenever it, or paintStyle, changes.
// we use paintStyle as the foundation and merge hoverPaintStyle over the
// top.
var _updateHoverStyle = function() {
if (self.paintStyle && self.hoverPaintStyle) {
var mergedHoverStyle = {};
jsPlumb.extend(mergedHoverStyle, self.paintStyle);
jsPlumb.extend(mergedHoverStyle, self.hoverPaintStyle);
delete self.hoverPaintStyle;
// we want the fillStyle of paintStyle to override a gradient, if possible.
if (mergedHoverStyle.gradient && self.paintStyle.fillStyle)
delete mergedHoverStyle.gradient;
self.hoverPaintStyle = mergedHoverStyle;
}
};
/*
* Sets the paint style and then repaints the element.
*
* Parameters:
* style - Style to use.
*/
this.setPaintStyle = function(style, doNotRepaint) {
self.paintStyle = style;
self.paintStyleInUse = self.paintStyle;
_updateHoverStyle();
if (!doNotRepaint) self.repaint();
};
/*
* Sets the paint style to use when the mouse is hovering over the element. This is null by default.
* The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
* it. This is because people will most likely want to change just one thing when hovering, say the
* color for example, but leave the rest of the appearance the same.
*
* Parameters:
* style - Style to use when the mouse is hovering.
* doNotRepaint - if true, the component will not be repainted. useful when setting things up initially.
*/
this.setHoverPaintStyle = function(style, doNotRepaint) {
self.hoverPaintStyle = style;
_updateHoverStyle();
if (!doNotRepaint) self.repaint();
};
/*
* sets/unsets the hover state of this element.
*
* Parameters:
* hover - hover state boolean
* ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
*/
this.setHover = function(hover, ignoreAttachedElements) {
_hover = hover;
if (self.hoverPaintStyle != null) {
self.paintStyleInUse = hover ? self.hoverPaintStyle : self.paintStyle;
self.repaint();
// get the list of other affected elements. for a connection, its the endpoints. for an endpoint, its the connections! surprise.
if (!ignoreAttachedElements)
_updateAttachedElements(hover);
}
};
this.isHover = function() {
return _hover;
};
this.attachListeners = function(o, c) {
var jpcl = jsPlumb.CurrentLibrary,
events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup" ],
eventFilters = { "mouseout":"mouseexit" },
bindOne = function(evt) {
var filteredEvent = eventFilters[evt] || evt;
jpcl.bind(o, evt, function(ee) {
c.fire(filteredEvent, c, ee);
});
};
for (var i = 0; i < events.length; i++) {
bindOne(events[i]);
}
};
var _updateAttachedElements = function(state) {
var affectedElements = self.getAttachedElements(); // implemented in subclasses
if (affectedElements) {
for (var i = 0; i < affectedElements.length; i++) {
affectedElements[i].setHover(state, true); // tell the attached elements not to inform their own attached elements.
}
}
};
};
var jsPlumbInstance = function(_defaults) {
/*
* Property: Defaults
*
* These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
* to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
* by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
*
* Properties:
* - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
* - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
* - *Connector* The default connector definition to use for all connections. Default is "Bezier".
* - *Container* Optional selector or element id that instructs jsPlumb to append elements it creates to a specific element.
* - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
* - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
* - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
* - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
* - *EndpointStyle* The default style definition to use for all endpoints. Default is fillStyle:"#456".
* - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
* - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
* - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
* - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
* - *LabelStyle* The default style to use for label overlays on connections.
* - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
* - *Overlays* The default overlay definitions. Defaults to an empty list.
* - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
* - *MouseEventsEnabled* Whether or not mouse events are enabled when using the canvas renderer. Defaults to true.
* The idea of this is just to give people a way to prevent all the mouse listeners from activating if they know they won't need mouse events.
* - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
* - *RenderMode* What mode to use to paint with. If you're on IE<9, you don't really get to choose this. You'll just get VML. Otherwise, the jsPlumb default is to use Canvas elements.
* - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
*/
this.Defaults = {
Anchor : "BottomCenter",
Anchors : [ null, null ],
Connector : "Bezier",
DragOptions : { },
DropOptions : { },
Endpoint : "Dot",
Endpoints : [ null, null ],
EndpointStyle : { fillStyle : "#456" },
EndpointStyles : [ null, null ],
EndpointHoverStyle : null,
EndpointHoverStyles : [ null, null ],
HoverPaintStyle : null,
LabelStyle : { color : "black" },
LogEnabled : false,
Overlays : [ ],
MaxConnections : 1,
MouseEventsEnabled : true,
PaintStyle : { lineWidth : 8, strokeStyle : "#456" },
RenderMode : "canvas",
Scope : "_jsPlumb_DefaultScope"
};
if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
this.logEnabled = this.Defaults.LogEnabled;
EventGenerator.apply(this);
var _bb = this.bind;
this.bind = function(event, fn) {
if ("ready" === event && initialized) fn();
else _bb(event, fn);
};
var _currentInstance = this,
log = null,
repaintFunction = function() {
jsPlumb.repaintEverything();
},
automaticRepaint = true,
repaintEverything = function() {
if (automaticRepaint)
repaintFunction();
},
resizeTimer = null,
initialized = false,
connectionsByScope = {},
/**
* map of element id -> endpoint lists. an element can have an arbitrary
* number of endpoints on it, and not all of them have to be connected
* to anything.
*/
endpointsByElement = {},
endpointsByUUID = {},
offsets = {},
offsetTimestamps = {},
floatingConnections = {},
draggableStates = {},
_mouseEventsEnabled = this.Defaults.MouseEventsEnabled,
_draggableByDefault = true,
canvasList = [],
sizes = [],
listeners = {}, // a map: keys are event types, values are lists of listeners.
DEFAULT_SCOPE = this.Defaults.Scope,
renderMode = null, // will be set in init()
/**
* helper method to add an item to a list, creating the list if it does
* not yet exist.
*/
_addToList = function(map, key, value) {
var l = map[key];
if (l == null) {
l = [];
map[key] = l;
}
l.push(value);
return l;
},
/**
* appends an element to some other element, which is calculated as follows:
*
* 1. if jsPlumb.Defaults.Container exists, use that element.
* 2. if the 'parent' parameter exists, use that.
* 3. otherwise just use the document body.
*
*/
_appendElement = function(el, parent) {
if (_currentInstance.Defaults.Container)
jsPlumb.CurrentLibrary.appendElement(el, _currentInstance.Defaults.Container);
else if (!parent)
document.body.appendChild(el);
else
jsPlumb.CurrentLibrary.appendElement(el, parent);
},
/**
* creates a timestamp, using milliseconds since 1970, but as a string.
*/
_timestamp = function() { return "" + (new Date()).getTime(); },
/**
* YUI, for some reason, put the result of a Y.all call into an object that contains
* a '_nodes' array, instead of handing back an array-like object like the other
* libraries do.
*/
_convertYUICollection = function(c) {
return c._nodes ? c._nodes : c;
},
/**
* Draws an endpoint and its connections.
*
* @param element element to draw (of type library specific element object)
* @param ui UI object from current library's event system. optional.
* @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
*/
_draw = function(element, ui, timestamp) {
var id = _getAttribute(element, "id");
var endpoints = endpointsByElement[id];
if (!timestamp) timestamp = _timestamp();
if (endpoints) {
_updateOffset( { elId : id, offset : ui, recalc : false, timestamp : timestamp }); // timestamp is checked against last update cache; it is
// valid for one paint cycle.
var myOffset = offsets[id], myWH = sizes[id];
for ( var i = 0; i < endpoints.length; i++) {
endpoints[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
var l = endpoints[i].connections;
for ( var j = 0; j < l.length; j++) {
l[j].paint( { elId : id, ui : ui, recalc : false, timestamp : timestamp }); // ...paint each connection.
// then, check for dynamic endpoint; need to repaint it.
var oIdx = l[j].endpoints[0] == endpoints[i] ? 1 : 0,
otherEndpoint = l[j].endpoints[oIdx];
if (otherEndpoint.anchor.isDynamic && !otherEndpoint.isFloating()) {
otherEndpoint.paint({ elementWithPrecedence:id });
// all the connections for the other endpoint now need to be repainted
for (var k = 0; k < otherEndpoint.connections.length; k++) {
if (otherEndpoint.connections[k] !== l)
otherEndpoint.connections[k].paint( { elId : id, ui : ui, recalc : false, timestamp : timestamp });
}
}
}
}
}
},
/**
* executes the given function against the given element if the first
* argument is an object, or the list of elements, if the first argument
* is a list. the function passed in takes (element, elementId) as
* arguments.
*/
_elementProxy = function(element, fn) {
var retVal = null;
if (element.constructor == Array) {
retVal = [];
for ( var i = 0; i < element.length; i++) {
var el = _getElementObject(element[i]), id = _getAttribute(el, "id");
retVal.push(fn(el, id)); // append return values to what we will return
}
} else {
var el = _getElementObject(element), id = _getAttribute(el, "id");
retVal = fn(el, id);
}
return retVal;
},
/**
* gets an Endpoint by uuid.
*/
_getEndpoint = function(uuid) { return endpointsByUUID[uuid]; },
/**
* inits a draggable if it's not already initialised.
*/
_initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
if (draggable) {
if (jsPlumb.CurrentLibrary.isDragSupported(element) && !jsPlumb.CurrentLibrary.isAlreadyDraggable(element)) {
var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
options = jsPlumb.extend( {}, options); // make a copy.
var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
options[dragEvent] = _wrap(options[dragEvent], function() {
var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
_draw(element, ui);
_addClass(element, "jsPlumb_dragged");
});
options[stopEvent] = _wrap(options[stopEvent], function() {
var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
_draw(element, ui);
_removeClass(element, "jsPlumb_dragged");
});
var draggable = draggableStates[_getId(element)];
options.disabled = draggable == null ? false : !draggable;
jsPlumb.CurrentLibrary.initDraggable(element, options);
}
}
},
_newConnection = function(params) {
var connectionFunc = jsPlumb.Defaults.ConnectionType || Connection,
endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint,
parent = jsPlumb.CurrentLibrary.getParent;
if (params.container)
params["parent"] = params.container;
else {
if (params.sourceEndpoint)
params["parent"] = params.sourceEndpoint.parent;
else if (params.source.constructor == endpointFunc)
params["parent"] = params.source.parent;
else params["parent"] = parent(params.source);
}
params["_jsPlumb"] = _currentInstance;
var con = new connectionFunc(params);
_eventFireProxy("click", "click", con);
_eventFireProxy("dblclick", "dblclick", con);
return con;
},
_eventFireProxy = function(event, proxyEvent, obj) {
obj.bind(event, function(e) {
_currentInstance.fire(proxyEvent, obj, e);
});
},
_newEndpoint = function(params) {
var endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint;
if (params.container)
params.parent = params.container;
else
params["parent"] = jsPlumb.CurrentLibrary.getParent(params.source);
params["_jsPlumb"] = _currentInstance,
ep = new endpointFunc(params);
_eventFireProxy("click", "endpointClick", ep);
_eventFireProxy("dblclick", "endpointDblClick", ep);
return ep;
},
/**
* performs the given function operation on all the connections found
* for the given element id; this means we find all the endpoints for
* the given element, and then for each endpoint find the connectors
* connected to it. then we pass each connection in to the given
* function.
*/
_operation = function(elId, func, endpointFunc) {
var endpoints = endpointsByElement[elId];
if (endpoints && endpoints.length) {
for ( var i = 0; i < endpoints.length; i++) {
for ( var j = 0; j < endpoints[i].connections.length; j++) {
var retVal = func(endpoints[i].connections[j]);
// if the function passed in returns true, we exit.
// most functions return false.
if (retVal) return;
}
if (endpointFunc) endpointFunc(endpoints[i]);
}
}
},
/**
* perform an operation on all elements.
*/
_operationOnAll = function(func) {
for ( var elId in endpointsByElement) {
_operation(elId, func);
}
},
/**
* helper to remove an element from the DOM.
*/
_removeElement = function(element, parent) {
if (element != null && element.parentNode != null) {
element.parentNode.removeChild(element);
}
},
/**
* helper to remove a list of elements from the DOM.
*/
_removeElements = function(elements, parent) {
for ( var i = 0; i < elements.length; i++)
_removeElement(elements[i], parent);
},
/**
* helper method to remove an item from a list.
*/
_removeFromList = function(map, key, value) {
if (key != null) {
var l = map[key];
if (l != null) {
var i = _findIndex(l, value);
if (i >= 0) {
delete (l[i]);
l.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Sets whether or not the given element(s) should be draggable,
* regardless of what a particular plumb command may request.
*
* @param element
* May be a string, a element objects, or a list of
* strings/elements.
* @param draggable
* Whether or not the given element(s) should be draggable.
*/
_setDraggable = function(element, draggable) {
return _elementProxy(element, function(el, id) {
draggableStates[id] = draggable;
if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
jsPlumb.CurrentLibrary.setDraggable(el, draggable);
}
});
},
/**
* private method to do the business of hiding/showing.
*
* @param el
* either Id of the element in question or a library specific
* object for the element.
* @param state
* String specifying a value for the css 'display' property
* ('block' or 'none').
*/
_setVisible = function(el, state, alsoChangeEndpoints) {
state = state === "block";
var endpointFunc = null;
if (alsoChangeEndpoints) {
if (state) endpointFunc = function(ep) {
ep.setVisible(true, true, true);
};
else endpointFunc = function(ep) {
ep.setVisible(false, true, true);
};
}
var id = _getAttribute(el, "id");
_operation(id, function(jpc) {
if (state && alsoChangeEndpoints) {
// this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
// this block will only set a connection to be visible if the other endpoint in the connection is also visible.
var oidx = jpc.sourceId === id ? 1 : 0;
if (jpc.endpoints[oidx].isVisible()) jpc.setVisible(true);
}
else // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
jpc.setVisible(state);
}, endpointFunc);
},
/**
* toggles the draggable state of the given element(s).
*
* @param el
* either an id, or an element object, or a list of
* ids/element objects.
*/
_toggleDraggable = function(el) {
return _elementProxy(el, function(el, elId) {
var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
state = !state;
draggableStates[elId] = state;
jsPlumb.CurrentLibrary.setDraggable(el, state);
return state;
});
},
/**
* private method to do the business of toggling hiding/showing.
*
* @param elId
* Id of the element in question
*/
_toggleVisible = function(elId, changeEndpoints) {
var endpointFunc = null;
if (changeEndpoints) {
endpointFunc = function(ep) {
var state = ep.isVisible();
ep.setVisible(!state);
};
}
_operation(elId, function(jpc) {
var state = jpc.isVisible();
jpc.setVisible(!state);
}, endpointFunc);
// todo this should call _elementProxy, and pass in the
// _operation(elId, f) call as a function. cos _toggleDraggable does
// that.
},
/**
* updates the offset and size for a given element, and stores the
* values. if 'offset' is not null we use that (it would have been
* passed in from a drag call) because it's faster; but if it is null,
* or if 'recalc' is true in order to force a recalculation, we get the current values.
*/
_updateOffset = function(params) {
var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId;
if (!recalc) {
if (timestamp && timestamp === offsetTimestamps[elId])
return offsets[elId];
}
if (recalc || offset == null) { // if forced repaint or no offset
// available, we recalculate.
// get the current size and offset, and store them
var s = _getElementObject(elId);
if (s != null) {
sizes[elId] = _getSize(s);
offsets[elId] = _getOffset(s);
offsetTimestamps[elId] = timestamp;
}
} else {
offsets[elId] = offset;
}
return offsets[elId];
},
/**
* gets an id for the given element, creating and setting one if
* necessary.
*/
_getId = function(element, uuid) {
var ele = _getElementObject(element);
var id = _getAttribute(ele, "id");
if (!id || id == "undefined") {
// check if fixed uuid parameter is given
if (arguments.length == 2 && arguments[1] != undefined)
id = uuid;
else
id = "jsPlumb_" + _timestamp();
_setAttribute(ele, "id", id);
}
return id;
},
/**
* wraps one function with another, creating a placeholder for the
* wrapped function if it was null. this is used to wrap the various
* drag/drop event functions - to allow jsPlumb to be notified of
* important lifecycle events without imposing itself on the user's
* drag/drop functionality. TODO: determine whether or not we should
* support an error handler concept, if one of the functions fails.
*
* @param wrappedFunction original function to wrap; may be null.
* @param newFunction function to wrap the original with.
* @param returnOnThisValue Optional. Indicates that the wrappedFunction should
* not be executed if the newFunction returns a value matching 'returnOnThisValue'.
* note that this is a simple comparison and only works for primitives right now.
*/
_wrap = function(wrappedFunction, newFunction, returnOnThisValue) {
wrappedFunction = wrappedFunction || function() { };
newFunction = newFunction || function() { };
return function() {
var r = null;
try {
r = newFunction.apply(this, arguments);
} catch (e) {
_log(_currentInstance, 'jsPlumb function failed : ' + e);
}
if (returnOnThisValue == null || (r !== returnOnThisValue)) {
try {
wrappedFunction.apply(this, arguments);
} catch (e) {
_log(_currentInstance, 'wrapped function failed : ' + e);
}
}
return r;
};
};
/*
* Property: connectorClass
* The CSS class to set on Connection elements. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
this.connectorClass = "_jsPlumb_connector";
/*
* Property: endpointClass
* The CSS class to set on Endpoint elements. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
this.endpointClass = "_jsPlumb_endpoint";
/*
* Property: overlayClass
* The CSS class to set on an Overlay that is an HTML element. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
this.overlayClass = "_jsPlumb_overlay";
this.Anchors = {};
this.Connectors = {
"canvas":{},
"svg":{},
"vml":{}
};
this.Endpoints = {
"canvas":{},
"svg":{},
"vml":{}
};
this.Overlays = {
"canvas":{},
"svg":{},
"vml":{}
};
// ************************ PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS *****************************************
/*
* Function: bind
* Bind to an event on jsPlumb.
*
* Parameters:
* event - the event to bind. Available events on jsPlumb are:
* - *jsPlumbConnection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
* - *jsPlumbConnectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
* - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
* - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
* - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
* - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
*
* callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
*/
/*
* Function: clearListeners
* Clears either all listeners, or listeners for some specific event.
*
* Parameters:
* event - optional. constrains the clear to just listeners for this event.
*/
// *************** END OF PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS ***********************************************************
/*
Function: addEndpoint
Adds an <Endpoint> to a given element or elements.
Parameters:
el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
this object are anything that 'params' can contain. See <Endpoint>.
Returns:
The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
See Also:
<addEndpoints>
*/
this.addEndpoint = function(el, params, referenceParams) {
referenceParams = referenceParams || {};
var p = jsPlumb.extend({}, referenceParams);
jsPlumb.extend(p, params);
p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
// YUI wrapper
el = _convertYUICollection(el);
var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
for (var i = 0; i < inputs.length; i++) {
var _el = _getElementObject(inputs[i]), id = _getId(_el);
p.source = _el;
_updateOffset({ elId : id });
var e = _newEndpoint(p);
_addToList(endpointsByElement, id, e);
var myOffset = offsets[id], myWH = sizes[id];
var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e });
e.paint({ anchorLoc : anchorLoc });
results.push(e);
}
return results.length == 1 ? results[0] : results;
};
/*
Function: addEndpoints
Adds a list of <Endpoint>s to a given element or elements.
Parameters:
target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some shared parameters that you wanted to reuse when you added Endpoints to a number of elements.
Returns:
List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
See Also:
<addEndpoint>
*/
this.addEndpoints = function(el, endpoints, referenceParams) {
var results = [];
for ( var i = 0; i < endpoints.length; i++) {
var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
if (e.constructor == Array)
Array.prototype.push.apply(results, e);
else results.push(e);
}
return results;
};
/*
Function: animate
This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
the 'step' function if necessary). This only supports the two-arg version of the animate call in jQuery, the one that takes an 'options' object as
the second arg. MooTools has only one method, a two arg one. Which is handy. YUI has a one-arg method, so jsPlumb merges 'properties' and 'options' together for YUI.
Parameters:
el - Element to animate. Either an id, or a selector representing the element.
properties - The 'properties' argument you want passed to the library's animate call.
options - The 'options' argument you want passed to the library's animate call.
Returns:
void
*/
this.animate = function(el, properties, options) {
var ele = _getElementObject(el), id = _getAttribute(el, "id");
options = options || {};
var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
options[stepFunction] = _wrap(options[stepFunction], function() {
_currentInstance.repaint(id);
});
// onComplete repaints, just to make sure everything looks good at the end of the animation.
options[completeFunction] = _wrap(options[completeFunction],
function() {
_currentInstance.repaint(id);
});
jsPlumb.CurrentLibrary.animate(ele, properties, options);
};
/*
Function: connect
Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
Parameters:
params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
Returns:
The newly created <Connection>.
*/
this.connect = function(params, referenceParams) {
var _p = jsPlumb.extend( {}, params);
if (referenceParams) jsPlumb.extend(_p, referenceParams);
if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source;
if (_p.source && _p.target.endpoint) _p.targetEndpoint = _p.target;
// test for endpoint uuids to connect
if (params.uuids) {
_p.sourceEndpoint = _getEndpoint(params.uuids[0]);
_p.targetEndpoint = _getEndpoint(params.uuids[1]);
}
// now ensure that if we do have Endpoints already, they're not full.
if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
_log(_currentInstance, "could not add connection; source endpoint is full");
return;
}
if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
_log(_currentInstance, "could not add connection; target endpoint is full");
return;
}
if (_p.target && !_p.target.endpoint) {
var tid = _getId(_p.target),
tep =_targetEndpointDefinitions[tid];
if (tep) {
if (_p.endpoints) _p.endpoints[1] = tep;
else if (_p.endpoint) {
_p.endpoints = [ _p.endpoint, tep ];
_p.endpoint = null;
}
else _p.endpoints = [ null, "Rectangle" ];
}
}
// dynamic anchors. backwards compatibility here: from 1.2.6 onwards you don't need to specify "dynamicAnchors". the fact that some anchor consists
// of multiple definitions is enough to tell jsPlumb you want it to be dynamic.
if (_p.dynamicAnchors) {
// these can either be an array of anchor coords, which we will use for both source and target, or an object with {source:[anchors], target:[anchors]}, in which
// case we will use a different set for each element.
var a = _p.dynamicAnchors.constructor == Array;
var sa = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.source));
var ta = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.target));
_p.anchors = [sa,ta];
}
var jpc = _newConnection(_p);
// add to list of connections (by scope).
_addToList(connectionsByScope, jpc.scope, jpc);
// fire an event
_currentInstance.fire("jsPlumbConnection", {
connection:jpc,
source : jpc.source, target : jpc.target,
sourceId : jpc.sourceId, targetId : jpc.targetId,
sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
});
// force a paint
_draw(jpc.source);
return jpc;
};
/*
Function: deleteEndpoint
Deletes an Endpoint and removes all Connections it has (which removes the Connections from the other Endpoints involved too)
Parameters:
object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
Returns:
void
*/
this.deleteEndpoint = function(object) {
var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object;
if (endpoint) {
var uuid = endpoint.getUuid();
if (uuid) endpointsByUUID[uuid] = null;
endpoint.detachAll();
_removeElement(endpoint.canvas, endpoint.parent);
// remove from endpointsbyElement
for (var e in endpointsByElement) {
var endpoints = endpointsByElement[e];
if (endpoints) {
var newEndpoints = [];
for (var i = 0; i < endpoints.length; i++)
if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
endpointsByElement[e] = newEndpoints;
}
}
delete endpoint;
}
};
/*
Function: deleteEveryEndpoint
Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
between this method and jsPlumb.reset).
Returns:
void
*/
this.deleteEveryEndpoint = function() {
for ( var id in endpointsByElement) {
var endpoints = endpointsByElement[id];
if (endpoints && endpoints.length) {
for ( var i = 0; i < endpoints.length; i++) {
_currentInstance.deleteEndpoint(endpoints[i]);
}
}
}
delete endpointsByElement;
endpointsByElement = {};
delete endpointsByUUID;
endpointsByUUID = {};
};
var fireDetachEvent = function(jpc) {
_currentInstance.fire("jsPlumbConnectionDetached", {
connection:jpc,
source : jpc.source, target : jpc.target,
sourceId : jpc.sourceId, targetId : jpc.targetId,
sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
});
};
/*
Function: detach
Detaches and then removes a <Connection>. Takes either (source, target) (the old way, maintained for backwards compatibility), or a params
object with various possible values.
Parameters:
source - id or element object of the first element in the Connection.
target - id or element object of the second element in the Connection.
params - a JS object containing the same parameters as you pass to jsPlumb.connect. If this is present then neither source nor
target should be present; it should be the only argument to the method. See the docs for <Connection>'s constructor for information
about the parameters allowed in the params object.
Returns:
true if successful, false if not.
*/
this.detach = function(source, target) {
if (arguments.length == 2) {
var s = _getElementObject(source), sId = _getId(s);
var t = _getElementObject(target), tId = _getId(t);
_operation(sId, function(jpc) {
if ((jpc.sourceId == sId && jpc.targetId == tId) || (jpc.targetId == sId && jpc.sourceId == tId)) {
_removeElements(jpc.connector.getDisplayElements(), jpc.parent);
jpc.endpoints[0].removeConnection(jpc);
jpc.endpoints[1].removeConnection(jpc);
_removeFromList(connectionsByScope, jpc.scope, jpc);
}
});
}
// this is the new version of the method, taking a JS object like
// the connect method does.
else if (arguments.length == 1) {
// TODO investigate whether or not this code still works when a user has supplied their own subclass of Connection. i suspect it may not.
if (arguments[0].constructor == Connection) {
arguments[0].endpoints[0].detachFrom(arguments[0].endpoints[1]);
}
else if (arguments[0].connection) {
arguments[0].connection.endpoints[0].detachFrom(arguments[0].connection.endpoints[1]);
}
else {
var _p = jsPlumb.extend( {}, source); // a backwards compatibility hack: source should be thought of as 'params' in this case.
// test for endpoint uuids to detach
if (_p.uuids) {
_getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]));
} else if (_p.sourceEndpoint && _p.targetEndpoint) {
_p.sourceEndpoint.detachFrom(_p.targetEndpoint);
} else {
var sourceId = _getId(_p.source);
var targetId = _getId(_p.target);
_operation(sourceId, function(jpc) {
if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
_removeElements(jpc.connector.getDisplayElements(), jpc.parent);
jpc.endpoints[0].removeConnection(jpc);
jpc.endpoints[1].removeConnection(jpc);
_removeFromList(connectionsByScope, jpc.scope, jpc);
}
});
}
}
}
};
/*
Function: detachAll
Removes all an element's Connections.
Parameters:
el - either the id of the element, or a selector for the element.
Returns:
void
*/
this.detachAllConnections = function(el) {
var id = _getAttribute(el, "id");
var endpoints = endpointsByElement[id];
if (endpoints && endpoints.length) {
for ( var i = 0; i < endpoints.length; i++) {
endpoints[i].detachAll();
}
}
};
/**
* @deprecated Use detachAllConnections instead. this will be removed in jsPlumb 1.3.
*/
this.detachAll = this.detachAllConnections;
/*
Function: detachEveryConnection
Remove all Connections from all elements, but leaves Endpoints in place.
Returns:
void
See Also:
<removeEveryEndpoint>
*/
this.detachEveryConnection = function() {
for ( var id in endpointsByElement) {
var endpoints = endpointsByElement[id];
if (endpoints && endpoints.length) {
for ( var i = 0; i < endpoints.length; i++) {
endpoints[i].detachAll();
}
}
}
delete connectionsByScope;
connectionsByScope = {};
};
/**
* @deprecated use detachEveryConnection instead. this will be removed in jsPlumb 1.3.
*/
this.detachEverything = this.detachEveryConnection;
/*
Function: draggable
Initialises the draggability of some element or elements. You should use this instead of you library's draggable method so that jsPlumb can setup the appropriate callbacks. Your underlying library's drag method is always called from this method.
Parameters:
el - either an element id, a list of element ids, or a selector.
options - options to pass through to the underlying library
Returns:
void
*/
this.draggable = function(el, options) {
if (typeof el == 'object' && el.length) {
for ( var i = 0; i < el.length; i++) {
var ele = _getElementObject(el[i]);
if (ele) _initDraggableIfNecessary(ele, true, options);
}
}
else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced
// into the library adapters (for jquery and mootools aswell)
for ( var i = 0; i < el._nodes.length; i++) {
var ele = _getElementObject(el._nodes[i]);
if (ele) _initDraggableIfNecessary(ele, true, options);
}
}
else {
var ele = _getElementObject(el);
if (ele) _initDraggableIfNecessary(ele, true, options);
}
};
/*
Function: extend
Wraps the underlying library's extend functionality.
Parameters:
o1 - object to extend
o2 - object to extend o1 with
Returns:
o1, extended with all properties from o2.
*/
this.extend = function(o1, o2) {
return jsPlumb.CurrentLibrary.extend(o1, o2);
};
/*
* Function: getDefaultEndpointType
* Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
* you would make a call like this in your class's constructor:
* jsPlumb.getDefaultEndpointType().apply(this, arguments);
*
* Returns:
* the default Endpoint function used by jsPlumb.
*/
this.getDefaultEndpointType = function() {
return Endpoint;
};
/*
* Function: getDefaultConnectionType
* Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
* you would make a call like this in your class's constructor:
* jsPlumb.getDefaultConnectionType().apply(this, arguments);
*
* Returns:
* the default Connection function used by jsPlumb.
*/
this.getDefaultConnectionType = function() {
return Connection;
};
/*
* Function: getConnections
* Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
* the result will be a list of connections having that scope (passing in no scope at all will result in jsPlumb assuming you want the
* default scope). If multiple scopes are passed in, the return value will be a map of { scope -> [ connection... ] }.
*
* Parameters
* scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
* of connections that are in the given scope.
* options - if the argument is a JS object, you can specify a finer-grained filter:
*
* - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes.
* - *source* either a string representing an element id, or a selector. constrains the result to connections having this source.
* - *target* either a string representing an element id, or a selector. constrains the result to connections having this target.
*
*/
this.getConnections = function(options) {
if (!options) {
options = {};
} else if (options.constructor == String) {
options = { "scope": options };
}
var prepareList = function(input) {
var r = [];
if (input) {
if (typeof input == 'string')
r.push(input);
else
r = input;
}
return r;
};
var scope = options.scope || jsPlumb.getDefaultScope(),
scopes = prepareList(scope),
sources = prepareList(options.source),
targets = prepareList(options.target),
filter = function(list, value) {
return list.length > 0 ? _findIndex(list, value) != -1 : true;
},
results = scopes.length > 1 ? {} : [],
_addOne = function(scope, obj) {
if (scopes.length > 1) {
var ss = results[scope];
if (ss == null) {
ss = []; results[scope] = ss;
}
ss.push(obj);
} else results.push(obj);
};
for ( var i in connectionsByScope) {
if (filter(scopes, i)) {
for ( var j = 0; j < connectionsByScope[i].length; j++) {
var c = connectionsByScope[i][j];
if (filter(sources, c.sourceId) && filter(targets, c.targetId))
_addOne(i, c);
}
}
}
return results;
};
/*
* Function: getAllConnections
* Gets all connections, as a map of { scope -> [ connection... ] }.
*/
this.getAllConnections = function() {
return connectionsByScope;
};
/*
* Function: getDefaultScope
* Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a
* scope to an endpoint or connection allows you to support different
* types of connections in the same UI. but if you're only interested in
* one type of connection, you don't need to supply a scope. this method
* will probably be used by very few people; it's good for testing
* though.
*/
this.getDefaultScope = function() {
return DEFAULT_SCOPE;
};
/*
Function: getEndpoint
Gets an Endpoint by UUID
Parameters:
uuid - the UUID for the Endpoint
Returns:
Endpoint with the given UUID, null if nothing found.
*/
this.getEndpoint = _getEndpoint;
/**
* Function:getEndpoints
* Gets the list of Endpoints for a given selector, or element id.
* @param el
* @return
*/
this.getEndpoints = function(el) {
return endpointsByElement[_getId(el)];
};
/*
* Gets an element's id, creating one if necessary. really only exposed
* for the lib-specific functionality to access; would be better to pass
* the current instance into the lib-specific code (even though this is
* a static call. i just don't want to expose it to the public API).
*/
this.getId = _getId;
this.appendElement = _appendElement;
/*
Function: hide
Sets an element's connections to be hidden.
Parameters:
el - either the id of the element, or a selector for the element.
changeEndpoints - whether not to also hide endpoints on the element. by default this is false.
Returns:
void
*/
this.hide = function(el, changeEndpoints) {
_setVisible(el, "none", changeEndpoints);
};
/**
* callback from the current library to tell us to prepare ourselves (attach
* mouse listeners etc; can't do that until the library has provided a bind method)
* @return
*/
this.init = function() {
if (!initialized) {
_currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run.
var _bind = function(event) {
jsPlumb.CurrentLibrary.bind(document, event, function(e) {
if (!_currentInstance.currentlyDragging && _mouseEventsEnabled && renderMode == jsPlumb.CANVAS) {
// try connections first
for (var scope in connectionsByScope) {
var c = connectionsByScope[scope];
for (var i = 0; i < c.length; i++) {
var t = c[i].connector[event](e);
if (t) return;
}
}
for (var el in endpointsByElement) {
var ee = endpointsByElement[el];
for (var i = 0; i < ee.length; i++) {
if (ee[i].endpoint[event](e)) return;
}
}
}
});
};
_bind("click");
_bind("dblclick");
_bind("mousemove");
_bind("mousedown");
_bind("mouseup");
initialized = true;
_currentInstance.fire("ready");
}
};
this.jsPlumbUIComponent = jsPlumbUIComponent;
this.EventGenerator = EventGenerator;
/*
* Creates an anchor with the given params.
*
* You do not need to use this method. It is exposed because of the way jsPlumb is
* split into three scripts; this will change in the future.
*
* x - the x location of the anchor as a fraction of the
* total width. y - the y location of the anchor as a fraction of the
* total height. xOrientation - value indicating the general direction a
* connection from the anchor should go in, in the x direction.
* yOrientation - value indicating the general direction a connection
* from the anchor should go in, in the y direction. xOffset - a fixed
* offset that should be applied in the x direction that should be
* applied after the x position has been figured out. optional. defaults
* to 0. yOffset - a fixed offset that should be applied in the y
* direction that should be applied after the y position has been
* figured out. optional. defaults to 0.
* -- OR --
*
* params - {x:..., y:..., xOrientation etc }
* -- OR FROM 1.2.4 ---
*
* name - the name of some Anchor in the _currentInstance.Anchors array.
* -- OR FROM 1.2.4 ---
*
* coords - a list of coords for the anchor, like you would pass to
* jsPlumb.makeAnchor (eg [0.5,0.5,0,-1] - an anchor in the center of
* some element, oriented towards the top of the screen)
* -- OR FROM 1.2.4 ---
*
* anchor - an existing anchor. just gets passed back. it's handy
* internally to have this functionality.
*
* Returns: The newly created Anchor.
*/
this.makeAnchor = function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
// backwards compatibility here. we used to require an object passed
// in but that makes the call very verbose. easier to use
// by just passing in four/six values. but for backwards
// compatibility if we are given only one value we assume it's a
// call in the old form.
if (arguments.length == 0) return null;
var params = {};
if (arguments.length == 1) {
var specimen = arguments[0];
// if it appears to be an anchor already...
if (specimen.compute && specimen.getOrientation) return specimen;
// is it the name of an anchor type?
else if (typeof specimen == "string") return _currentInstance.Anchors[arguments[0]]();
// is it an array of coordinates?
else if (specimen.constructor == Array) {
if (specimen[0].constructor == Array || specimen[0].constructor == String)
return new DynamicAnchor(specimen);
else
return jsPlumb.makeAnchor.apply(this, specimen);
}
// last we try the backwards compatibility stuff.
else if (typeof arguments[0] == "object") jsPlumb.extend(params, x);
} else {
params = { x : x, y : y };
if (arguments.length >= 4) params.orientation = [ arguments[2], arguments[3] ];
if (arguments.length == 6) params.offsets = [ arguments[4], arguments[5] ];
}
var a = new Anchor(params);
a.clone = function() {
return new Anchor(params);
};
return a;
};
/**
* makes a list of anchors from the given list of types or coords, eg
* ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
*/
this.makeAnchors = function(types) {
var r = [];
for ( var i = 0; i < types.length; i++)
if (typeof types[i] == "string")
r.push(_currentInstance.Anchors[types[i]]());
else if (types[i].constructor == Array)
r.push(jsPlumb.makeAnchor(types[i]));
return r;
};
/**
* Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
* objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
* not need to provide this - i think).
*/
this.makeDynamicAnchor = function(anchors, anchorSelector) {
return new DynamicAnchor(anchors, anchorSelector);
};
/**
* Function: makeTarget
* Makes some DOM element a Connection target, allowing you to drag connections to it
* without having to register any Endpoints on it first. When a Connection is established,
* the endpoint spec that was passed in to this method is used to create a suitable
* Endpoint (the default will be used if you do not provide one).
*
* Parameters:
* el - string id or element selector for the element to make a target.
* params - JS object containing parameters:
* endpoint optional. specification of an endpoint to create when a connection is created.
* scope optional. scope for the drop zone.
* dropOptions optional. same stuff as you would pass to dropOptions of an Endpoint definition.
* deleteEndpointsOnDetach optional, defaults to false. whether or not to delete
* any Endpoints created by a connection to this target if
* the connection is subsequently detached. this will not
* remove Endpoints that have had more Connections attached
* to them after they were created.
*
*
*/
var _targetEndpointDefinitions = {};
this.makeTarget = function(el, params, referenceParams) {
var p = jsPlumb.extend({}, referenceParams);
jsPlumb.extend(p, params);
var jpcl = jsPlumb.CurrentLibrary,
scope = p.scope || _currentInstance.Defaults.Scope,
deleteEndpointsOnDetach = p.deleteEndpointsOnDetach || false,
_doOne = function(_el) {
// get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
// and use the endpoint definition if found.
var elid = _getId(_el);
_targetEndpointDefinitions[elid] = p.endpoint;
var dropOptions = jsPlumb.extend({}, p.dropOptions || {});
var _drop = function() {
var draggable = _getElementObject(jpcl.getDragObject(arguments)),
id = _getAttribute(draggable, "dragId"),
// restore the original scope if necessary (issue 57)
scope = _getAttribute(draggable, "originalScope");
if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
// get the connection, to then get its endpoint
var jpc = floatingConnections[id],
source = jpc.endpoints[0],
_endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : null,
// make a new Endpoint
newEndpoint = jsPlumb.addEndpoint(_el, _endpoint);
var c = jsPlumb.connect({
source:source,
target:newEndpoint,
scope:scope
});
if (deleteEndpointsOnDetach)
c.endpointToDeleteOnDetach = newEndpoint;
};
var dropEvent = jpcl.dragEvents['drop'];
dropOptions["scope"] = dropOptions["scope"] || scope;
dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop);
jpcl.initDroppable(_el, dropOptions);
};
el = _convertYUICollection(el);
var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
for (var i = 0; i < inputs.length; i++) {
_doOne(_getElementObject(inputs[i]));
}
};
/**
* helper method to make a list of elements drop targets.
* @param els
* @param params
* @param referenceParams
* @return
*/
this.makeTargets = function(els, params, referenceParams) {
for ( var i = 0; i < els.length; i++) {
_currentInstance.makeTarget(els[i], params, referenceParams);
}
};
/*
Function: ready
Helper method to bind a function to jsPlumb's ready event.
*/
this.ready = function(fn) {
_currentInstance.bind("ready", fn);
},
/*
Function: repaint
Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
Parameters:
el - either the id of the element or a selector representing the element.
Returns:
void
See Also:
<repaintEverything>
*/
this.repaint = function(el) {
var _processElement = function(el) { _draw(_getElementObject(el)); };
// support both lists...
if (typeof el == 'object')
for ( var i = 0; i < el.length; i++) _processElement(el[i]);
else // ...and single strings.
_processElement(el);
};
/*
Function: repaintEverything
Repaints all connections.
Returns:
void
See Also:
<repaint>
*/
this.repaintEverything = function() {
var timestamp = _timestamp();
for ( var elId in endpointsByElement) {
_draw(_getElementObject(elId), null, timestamp);
}
};
/*
Function: removeAllEndpoints
Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
Parameters:
el - either an element id, or a selector for an element.
Returns:
void
See Also:
<removeEndpoint>
*/
this.removeAllEndpoints = function(el) {
var elId = _getAttribute(el, "id");
var ebe = endpointsByElement[elId];
for ( var i in ebe)
_currentInstance.deleteEndpoint(ebe[i]);
endpointsByElement[elId] = [];
};
/*
Removes every Endpoint in this instance of jsPlumb.
@deprecated use deleteEveryEndpoint instead
*/
this.removeEveryEndpoint = this.deleteEveryEndpoint;
/*
Removes the given Endpoint from the given element.
@deprecated Use jsPlumb.deleteEndpoint instead (and note you dont need to supply the element. it's irrelevant).
*/
this.removeEndpoint = function(el, endpoint) {
_currentInstance.deleteEndpoint(endpoint);
};
/*
Function:reset
Removes all endpoints and connections and clears the listener list. To keep listeners call jsPlumb.deleteEveryEndpoint instead of this.
*/
this.reset = function() {
this.deleteEveryEndpoint();
this.clearListeners();
};
/*
Function: setAutomaticRepaint
Sets/unsets automatic repaint on window resize.
Parameters:
value - whether or not to automatically repaint when the window is resized.
Returns: void
*/
this.setAutomaticRepaint = function(value) {
automaticRepaint = value;
};
/*
* Function: setDefaultScope
* Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
* scope to an Endpoint or Connection allows you to support different
* types of Connections in the same UI. If you're only interested in
* one type of Connection, you don't need to supply a scope. This method
* will probably be used by very few people; it just instructs jsPlumb
* to use a different key for the default scope.
*
* Parameters:
* scope - scope to set as default.
*/
this.setDefaultScope = function(scope) {
DEFAULT_SCOPE = scope;
};
/*
* Function: setDraggable
* Sets whether or not a given element is
* draggable, regardless of what any jsPlumb command may request.
*
* Parameters:
* el - either the id for the element, or a selector representing the element.
*
* Returns:
* void
*/
this.setDraggable = _setDraggable;
/*
* Function: setDraggableByDefault
* Sets whether or not elements are draggable by default. Default for this is true.
*
* Parameters:
* draggable - value to set
*
* Returns:
* void
*/
this.setDraggableByDefault = function(draggable) {
_draggableByDefault = draggable;
};
this.setDebugLog = function(debugLog) {
log = debugLog;
};
/*
* Function: setRepaintFunction
* Sets the function to fire when the window size has changed and a repaint was fired.
*
* Parameters:
* f - Function to execute.
*
* Returns: void
*/
this.setRepaintFunction = function(f) {
repaintFunction = f;
};
/*
* Function: setMouseEventsEnabled
* Sets whether or not mouse events are enabled. Default is true.
*
* Parameters:
* enabled - whether or not mouse events should be enabled.
*
* Returns:
* void
*/
this.setMouseEventsEnabled = function(enabled) {
_mouseEventsEnabled = enabled;
};
/*
* Constant for use with the setRenderMode method
*/
this.CANVAS = "canvas";
/*
* Constant for use with the setRenderMode method
*/
this.SVG = "svg";
this.VML = "vml";
/*
* Function: setRenderMode
* Sets render mode: jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that
* what you asked for is not supported (and that VML is). If you asked for VML but the browser does
* not support it, jsPlumb uses SVG.
*
* Returns:
* the render mode that jsPlumb set, which of course may be different from that requested.
*/
this.setRenderMode = function(mode) {
if (mode)
mode = mode.toLowerCase();
else
return;
if (mode !== jsPlumb.CANVAS && mode !== jsPlumb.SVG && mode !== jsPlumb.VML) throw new Error("render mode must be one of jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML");
// now test we actually have the capability to do this.
if (mode === jsPlumb.CANVAS && canvasAvailable)
renderMode = jsPlumb.CANVAS;
else if (mode === jsPlumb.SVG && svgAvailable)
renderMode = jsPlumb.SVG;
else if (vmlAvailable)
renderMode = jsPlumb.VML;
return renderMode;
};
this.getRenderMode = function() { return renderMode; };
/*
* Function: show
* Sets an element's connections to be visible.
*
* Parameters:
* el - either the id of the element, or a selector for the element.
* changeEndpoints - whether or not to also change the visible state of the endpoints on the element. this also has a bearing on
* other connections on those endpoints: if their other endpoint is also visible, the connections are made visible.
*
* Returns:
* void
*/
this.show = function(el, changeEndpoints) {
_setVisible(el, "block", changeEndpoints);
};
/*
* Function: sizeCanvas
* Helper to size a canvas. You would typically use
* this when writing your own Connector or Endpoint implementation.
*
* Parameters:
* x - [int] x position for the Canvas origin
* y - [int] y position for the Canvas origin
* w - [int] width of the canvas
* h - [int] height of the canvas
*
* Returns:
* void
*/
this.sizeCanvas = function(canvas, x, y, w, h) {
if (canvas) {
canvas.style.height = h + "px";
canvas.height = h;
canvas.style.width = w + "px";
canvas.width = w;
canvas.style.left = x + "px";
canvas.style.top = y + "px";
}
};
/**
* gets some test hooks. nothing writable.
*/
this.getTestHarness = function() {
return {
endpointsByElement : endpointsByElement,
endpointCount : function(elId) {
var e = endpointsByElement[elId];
return e ? e.length : 0;
},
connectionCount : function(scope) {
scope = scope || DEFAULT_SCOPE;
var c = connectionsByScope[scope];
return c ? c.length : 0;
},
findIndex : _findIndex,
getId : _getId,
makeAnchor:self.makeAnchor,
makeDynamicAnchor:self.makeDynamicAnchor
};
};
/**
* Toggles visibility of an element's connections. kept for backwards
* compatibility
*/
this.toggle = _toggleVisible;
/*
* Function: toggleVisible
* Toggles visibility of an element's Connections.
*
* Parameters:
* el - either the element's id, or a selector representing the element.
* changeEndpoints - whether or not to also toggle the endpoints on the element.
*
* Returns:
* void, but should be updated to return the current state
*/
// TODO: update this method to return the current state.
this.toggleVisible = _toggleVisible;
/*
* Function: toggleDraggable
* Toggles draggability (sic?) of an element's Connections.
*
* Parameters:
* el - either the element's id, or a selector representing the element.
*
* Returns:
* The current draggable state.
*/
this.toggleDraggable = _toggleDraggable;
/*
* Function: unload
* Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element.
*
* Returns:
* void
*/
this.unload = function() {
delete endpointsByElement;
delete endpointsByUUID;
delete offsets;
delete sizes;
delete floatingConnections;
delete draggableStates;
delete canvasList;
};
/*
* Helper method to wrap an existing function with one of
* your own. This is used by the various implementations to wrap event
* callbacks for drag/drop etc; it allows jsPlumb to be transparent in
* its handling of these things. If a user supplies their own event
* callback, for anything, it will always be called.
*/
this.wrap = _wrap;
this.addListener = this.bind;
/**
* Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user
* was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"),
* or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the
* creation of Anchors without user intervention.
*/
var Anchor = function(params) {
var self = this;
this.x = params.x || 0;
this.y = params.y || 0;
var orientation = params.orientation || [ 0, 0 ];
var lastTimestamp = null, lastReturnValue = null;
this.offsets = params.offsets || [ 0, 0 ];
self.timestamp = null;
this.compute = function(params) {
var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
if (timestamp && timestamp === self.timestamp) {
return lastReturnValue;
}
lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
// adjust loc if there is an offsetParent
if (element.canvas && element.canvas.offsetParent) {
var po = element.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(element.canvas.offsetParent);
lastReturnValue[0] = lastReturnValue[0] - po.left;
lastReturnValue[1] = lastReturnValue[1] - po.top;
}
self.timestamp = timestamp;
return lastReturnValue;
};
this.getOrientation = function() { return orientation; };
this.equals = function(anchor) {
if (!anchor) return false;
var ao = anchor.getOrientation();
var o = this.getOrientation();
return this.x == anchor.x && this.y == anchor.y
&& this.offsets[0] == anchor.offsets[0]
&& this.offsets[1] == anchor.offsets[1]
&& o[0] == ao[0] && o[1] == ao[1];
};
this.getCurrentLocation = function() { return lastReturnValue; };
};
/**
* An Anchor that floats. its orientation is computed dynamically from
* its position relative to the anchor it is floating relative to. It is used when creating
* a connection through drag and drop.
*
* TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
*/
var FloatingAnchor = function(params) {
// this is the anchor that this floating anchor is referenced to for
// purposes of calculating the orientation.
var ref = params.reference;
// the canvas this refers to.
var refCanvas = params.referenceCanvas;
var size = _getSize(_getElementObject(refCanvas));
// these are used to store the current relative position of our
// anchor wrt the reference anchor. they only indicate
// direction, so have a value of 1 or -1 (or, very rarely, 0). these
// values are written by the compute method, and read
// by the getOrientation method.
var xDir = 0, yDir = 0;
// temporary member used to store an orientation when the floating
// anchor is hovering over another anchor.
var orientation = null;
var _lastResult = null;
this.compute = function(params) {
var xy = params.xy, element = params.element;
var result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
// adjust loc if there is an offsetParent
if (element.canvas && element.canvas.offsetParent) {
var po = element.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(element.canvas.offsetParent);
result[0] = result[0] - po.left;
result[1] = result[1] - po.top;
}
_lastResult = result;
return result;
};
this.getOrientation = function() {
if (orientation) return orientation;
else {
var o = ref.getOrientation();
// here we take into account the orientation of the other
// anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
// up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
return [ Math.abs(o[0]) * xDir * -1,
Math.abs(o[1]) * yDir * -1 ];
}
};
/**
* notification the endpoint associated with this anchor is hovering
* over another anchor; we want to assume that anchor's orientation
* for the duration of the hover.
*/
this.over = function(anchor) { orientation = anchor.getOrientation(); };
/**
* notification the endpoint associated with this anchor is no
* longer hovering over another anchor; we should resume calculating
* orientation as we normally do.
*/
this.out = function() { orientation = null; };
this.getCurrentLocation = function() { return _lastResult; };
};
/*
* A DynamicAnchors is an Anchor that contains a list of other Anchors, which it cycles
* through at compute time to find the one that is located closest to
* the center of the target element, and returns that Anchor's compute
* method result. this causes endpoints to follow each other with
* respect to the orientation of their target elements, which is a useful
* feature for some applications.
*
*/
var DynamicAnchor = function(anchors, anchorSelector) {
this.isSelective = true;
this.isDynamic = true;
var _anchors = [],
_convert = function(anchor) { return anchor.constructor == Anchor ? anchor: jsPlumb.makeAnchor(anchor); };
for (var i = 0; i < anchors.length; i++) _anchors[i] = _convert(anchors[i]);
this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
this.getAnchors = function() { return _anchors; };
this.locked = false;
var _curAnchor = _anchors.length > 0 ? _anchors[0] : null,
_curIndex = _anchors.length > 0 ? 0 : -1,
self = this,
// helper method to calculate the distance between the centers of the two elements.
_distance = function(anchor, cx, cy, xy, wh) {
var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
},
// default method uses distance between element centers. you can provide your own method in the dynamic anchor
// constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
// xy - xy loc of the anchor's element
// wh - anchor's element's dimensions
// txy - xy loc of the element of the other anchor in the connection
// twh - dimensions of the element of the other anchor in the connection.
// anchors - the list of selectable anchors
_anchorSelector = anchorSelector || function(xy, wh, txy, twh, anchors) {
var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
var minIdx = -1, minDist = Infinity;
for ( var i = 0; i < anchors.length; i++) {
var d = _distance(anchors[i], cx, cy, xy, wh);
if (d < minDist) {
minIdx = i + 0;
minDist = d;
}
}
return anchors[minIdx];
};
this.compute = function(params) {
var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
// if anchor is locked or an opposite element was not given, we
// maintain our state. anchor will be locked
// if it is the source of a drag and drop.
if (self.locked || txy == null || twh == null)
return _curAnchor.compute(params);
else
params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
_curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
var pos = _curAnchor.compute(params);
return pos;
};
this.getCurrentLocation = function() {
var cl = _curAnchor != null ? _curAnchor.getCurrentLocation() : null;
return cl;
};
this.getOrientation = function() { return _curAnchor != null ? _curAnchor.getOrientation() : [ 0, 0 ]; };
this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
};
/*
* Class: Connection
* The connecting line between two Endpoints.
*/
/*
* Function: Connection
* Connection constructor.
*
* Parameters:
* source - either an element id, a selector for an element, or an Endpoint.
* target - either an element id, a selector for an element, or an Endpoint
* scope - scope descriptor for this connection. optional.
* container - optional id or selector instructing jsPlumb where to attach all the elements it creates for this connection. you should read the documentation for a full discussion of this.
* endpoint - Optional. Endpoint definition to use for both ends of the connection.
* endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
* endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
* endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
* paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
* hoverPaintStyle - Parameters defining the appearance of the Connection when the mouse is hovering over it. Optional; jsPlumb will use the defaults if you supply nothing here (note that the default hoverPaintStyle is null).
* overlays - Optional array of Overlay definitions to appear on this Connection.
* drawEndpoints - if false, instructs jsPlumb to not draw the endpoints for this Connection. Be careful with this: it only really works when you tell jsPlumb to attach elements to the document body. Read the documentation for a full discussion of this.
*/
var Connection = function(params) {
jsPlumbUIComponent.apply(this, arguments);
// ************** get the source and target and register the connection. *******************
var self = this;
var visible = true;
/**
Function:isVisible
Returns whether or not the Connection is currently visible.
*/
this.isVisible = function() { return visible; };
/**
Function: setVisible
Sets whether or not the Connection should be visible.
Parameters:
visible - boolean indicating desired visible state.
*/
this.setVisible = function(v) {
visible = v;
if (self.connector && self.connector.canvas) self.connector.canvas.style.display = v ? "block" : "none";
};
var id = new String('_jsplumb_c_' + (new Date()).getTime());
this.getId = function() { return id; };
this.parent = params.parent;
/**
Property: source
The source element for this Connection.
*/
this.source = _getElementObject(params.source);
/**
Property:target
The target element for this Connection.
*/
this.target = _getElementObject(params.target);
// sourceEndpoint and targetEndpoint override source/target, if they are present.
if (params.sourceEndpoint) this.source = params.sourceEndpoint.getElement();
if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
/*
* Property: sourceId
* Id of the source element in the connection.
*/
this.sourceId = _getAttribute(this.source, "id");
/*
* Property: targetId
* Id of the target element in the connection.
*/
this.targetId = _getAttribute(this.target, "id");
this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
/**
* implementation of abstract method in EventGenerator
* @return list of attached elements. in our case, a list of Endpoints.
*/
this.getAttachedElements = function() {
return self.endpoints;
};
/**
* implementation of abstract method in EventGenerator
*/
var srcWhenMouseDown = null, targetWhenMouseDown = null;
this.savePosition = function() {
srcWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.source));
targetWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.target));
};
/*
* Property: scope
* Optional scope descriptor for the connection.
*/
this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints.
/*
* Property: endpoints
* Array of [source, target] Endpoint objects.
*/
this.endpoints = [];
this.endpointStyles = [];
// wrapped the main function to return null if no input given. this lets us cascade defaults properly.
var _makeAnchor = function(anchorParams) {
if (anchorParams)
return jsPlumb.makeAnchor(anchorParams);
};
var prepareEndpoint = function(existing, index, params, element, connectorPaintStyle, connectorHoverPaintStyle) {
if (existing) {
self.endpoints[index] = existing;
existing.addConnection(self);
} else {
if (!params.endpoints) params.endpoints = [ null, null ];
var ep = params.endpoints[index]
|| params.endpoint
|| _currentInstance.Defaults.Endpoints[index]
|| jsPlumb.Defaults.Endpoints[index]
|| _currentInstance.Defaults.Endpoint
|| jsPlumb.Defaults.Endpoint;
if (!params.endpointStyles) params.endpointStyles = [ null, null ];
if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
// Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
if (es.fillStyle == null && connectorPaintStyle != null)
es.fillStyle = connectorPaintStyle.strokeStyle;
// TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
//*
if (es.outlineColor == null && connectorPaintStyle != null)
es.outlineColor = connectorPaintStyle.outlineColor;
if (es.outlineWidth == null && connectorPaintStyle != null)
es.outlineWidth = connectorPaintStyle.outlineWidth;
//*/
var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _currentInstance.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
// endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
if (connectorHoverPaintStyle != null) {
if (ehs == null) ehs = {};
if (ehs.fillStyle == null) {
ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
}
}
var a = params.anchors ? params.anchors[index] : _makeAnchor(_currentInstance.Defaults.Anchors[index]) || _makeAnchor(jsPlumb.Defaults.Anchors[index]) || _makeAnchor(_currentInstance.Defaults.Anchor) || _makeAnchor(jsPlumb.Defaults.Anchor);
var u = params.uuids ? params.uuids[index] : null;
var e = _newEndpoint({
paintStyle : es,
hoverPaintStyle:ehs,
endpoint : ep,
connections : [ self ],
uuid : u,
anchor : a,
source : element,
container:params.container
});
self.endpoints[index] = e;
if (params.drawEndpoints === false) e.setVisible(false, true, true);
return e;
}
};
var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source, params.paintStyle, params.hoverPaintStyle);
if (eS) _addToList(endpointsByElement, this.sourceId, eS);
var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target, params.paintStyle, params.hoverPaintStyle);
if (eT) _addToList(endpointsByElement, this.targetId, eT);
// if scope not set, set it to be the scope for the source endpoint.
if (!this.scope) this.scope = this.endpoints[0].scope;
/*
* Function: setConnector
* Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method - the same
* thing that you would set as the 'connector' property on a jsPlumb.connect call.
*
* Parameters:
* connector - Connector definition
*/
this.setConnector = function(connector, doNotRepaint) {
if (self.connector != null) _removeElements(self.connector.getDisplayElements(), self.parent);
var connectorArgs = { _jsPlumb:self._jsPlumb, parent:params.parent, cssClass:params.cssClass, container:params.container };
if (connector.constructor == String)
this.connector = new jsPlumb.Connectors[renderMode][connector](connectorArgs); // lets you use a string as shorthand.
else if (connector.constructor == Array)
this.connector = new jsPlumb.Connectors[renderMode][connector[0]](jsPlumb.extend(connector[1], connectorArgs));
this.canvas = this.connector.canvas;
var _mouseDown = false, _mouseWasDown = false, _mouseDownAt = null;
// add mouse events
this.connector.bind("click", function(con, e) {
_mouseWasDown = false;
self.fire("click", self, e);
});
this.connector.bind("dblclick", function(con, e) { _mouseWasDown = false;self.fire("dblclick", self, e); });
this.connector.bind("mouseenter", function(con, e) {
if (!self.isHover()) {
if (_connectionBeingDragged == null) {
self.setHover(true);
}
self.fire("mouseenter", self, e);
}
});
this.connector.bind("mouseexit", function(con, e) {
if (self.isHover()) {
if (_connectionBeingDragged == null) {
self.setHover(false);
}
self.fire("mouseexit", self, e);
}
});
this.connector.bind("mousedown", function(con, e) {
_mouseDown = true;
_mouseDownAt = jsPlumb.CurrentLibrary.getPageXY(e);
self.savePosition();
});
this.connector.bind("mouseup", function(con, e) {
_mouseDown = false;
if (self.connector == _connectionBeingDragged) _connectionBeingDragged = null;
});
if (!doNotRepaint) self.repaint();
};
/*
* Property: connector
* The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
*/
self.setConnector(this.endpoints[0].connector ||
this.endpoints[1].connector ||
params.connector ||
_currentInstance.Defaults.Connector ||
jsPlumb.Defaults.Connector, true);
this.setPaintStyle(this.endpoints[0].connectorStyle ||
this.endpoints[1].connectorStyle ||
params.paintStyle ||
_currentInstance.Defaults.PaintStyle ||
jsPlumb.Defaults.PaintStyle, true);
this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
this.endpoints[1].connectorHoverStyle ||
params.hoverPaintStyle ||
_currentInstance.Defaults.HoverPaintStyle ||
jsPlumb.Defaults.HoverPaintStyle, true);
this.paintStyleInUse = this.paintStyle;
/*
* Property: overlays
* List of Overlays for this Connection.
*/
this.overlays = [];
var _overlays = params.overlays || _currentInstance.Defaults.Overlays;
if (_overlays) {
for (var i = 0; i < _overlays.length; i++) {
var o = _overlays[i], _newOverlay = null, _overlayEvents = null;
if (o.constructor == Array) { // this is for the shorthand ["Arrow", { width:50 }] syntax
// there's also a three arg version:
// ["Arrow", { width:50 }, {location:0.7}]
// which merges the 3rd arg into the 2nd.
var type = o[0];
var p = jsPlumb.CurrentLibrary.extend({connection:self, _jsPlumb:_currentInstance}, o[1]); // make a copy of the object so as not to mess up anyone else's reference...
if (o.length == 3) jsPlumb.CurrentLibrary.extend(p, o[2]);
_newOverlay = new jsPlumb.Overlays[renderMode][type](p);
if (p.events) {
for (var evt in p.events) {
_newOverlay.bind(evt, p.events[evt]);
}
}
} else if (o.constructor == String) {
_newOverlay = new jsPlumb.Overlays[renderMode][o]({connection:self, _jsPlumb:_currentInstance});
} else {
_newOverlay = o;
}
this.overlays.push(_newOverlay);
}
}
// ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
/*
* Function: bind
* Bind to an event on the Connection.
*
* Parameters:
* event - the event to bind. Available events on a Connection are:
* - *click* : notification that a Connection was clicked.
* - *dblclick* : notification that a Connection was double clicked.
* - *mouseenter* : notification that the mouse is over a Connection.
* - *mouseexit* : notification that the mouse exited a Connection.
*
* callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
*/
/*
* Function: setPaintStyle
* Sets the Connection's paint style and then repaints the Connection.
*
* Parameters:
* style - Style to use.
*/
/*
* Function: setHoverPaintStyle
* Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
* The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
* it. This is because people will most likely want to change just one thing when hovering, say the
* color for example, but leave the rest of the appearance the same.
*
* Parameters:
* style - Style to use when the mouse is hovering.
* doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
*/
/*
* Function: setHover
* Sets/unsets the hover state of this Connection.
*
* Parameters:
* hover - hover state boolean
* ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
*/
// ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
/*
* Function: addOverlay
* Adds an Overlay to the Connection.
*
* Parameters:
* overlay - Overlay to add.
*/
this.addOverlay = function(overlay) { self.overlays.push(overlay); };
/**
* Function: removeAllOverlays
* Removes all overlays from the Connection, and then repaints.
*/
this.removeAllOverlays = function() {
self.overlays.splice(0, self.overlays.length);
self.repaint();
};
/**
* Function:removeOverlay
* Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
* Parameters:
* overlayId - id of the overlay to remove.
*/
this.removeOverlay = function(overlayId) {
var idx = -1;
for (var i = 0; i < self.overlays.length; i++) {
if (overlayId === self.overlays[i].id) {
idx = i;
break;
}
}
if (idx != -1) self.overlays.splice(idx, 1);
};
/**
* Function:removeOverlay
* Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
* Parameters:
* overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
*/
this.removeOverlays = function() {
for (var i = 0; i < arguments.length; i++)
self.removeOverlay(arguments[i]);
};
// this is a shortcut helper method to let people add a label as
// overlay.
this.labelStyle = params.labelStyle || _currentInstance.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;
this.label = params.label;
if (this.label) {
this.overlays.push(new jsPlumb.Overlays[renderMode].Label( {
cssClass:params.cssClass,
labelStyle : this.labelStyle,
label : this.label,
connection:self,
_jsPlumb:_currentInstance
}));
}
_updateOffset( { elId : this.sourceId });
_updateOffset( { elId : this.targetId });
/*
* Function: setLabel
* Sets the Connection's label.
*
* Parameters:
* l - label to set. May be a String or a Function that returns a String.
*/
this.setLabel = function(l) {
self.label = l;
_currentInstance.repaint(self.source);
};
// paint the endpoints
var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
var otherOffset = offsets[this.targetId];
var otherWH = sizes[this.targetId];
var anchorLoc = this.endpoints[0].anchor.compute( {
xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1]
});
this.endpoints[0].paint( { anchorLoc : anchorLoc });
anchorLoc = this.endpoints[1].anchor.compute( {
xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0]
});
this.endpoints[1].paint({ anchorLoc : anchorLoc });
/*
* Paints the Connection. Not exposed for public usage.
*
* Parameters:
* elId - Id of the element that is in motion.
* ui - current library's event system ui object (present if we came from a drag to get here).
* recalc - whether or not to recalculate all anchors etc before painting.
* timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
*/
this.paint = function(params) {
params = params || {};
var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp;
var fai = self.floatingAnchorIndex;
// if the moving object is not the source we must transpose the two references.
var swap = false;
var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
var el = swap ? this.target : this.source;
_updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp });
_updateOffset( { elId : tId, timestamp : timestamp }); // update the target if this is a forced repaint. otherwise, only the source has been moved.
var sAnchorP = this.endpoints[sIdx].anchor.getCurrentLocation();
var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
var tAnchorP = this.endpoints[tIdx].anchor.getCurrentLocation();
var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
/* paint overlays*/
var maxSize = 0;
for ( var i = 0; i < self.overlays.length; i++) {
var o = self.overlays[i];
var s = o.computeMaxSize(self.connector);
if (s > maxSize)
maxSize = s;
}
var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, self.paintStyleInUse.lineWidth, maxSize);
self.connector.paint(dim, self.paintStyleInUse);
/* paint overlays*/
for ( var i = 0; i < self.overlays.length; i++) {
var o = self.overlays[i];
self.overlayPlacements[i] = o.draw(self.connector, self.paintStyleInUse, dim);
}
};
/*
* Function: repaint
* Repaints the Connection.
*/
this.repaint = function() {
this.paint({ elId : this.sourceId, recalc : true });
};
_initDraggableIfNecessary(self.source, params.draggable, params.dragOptions);
_initDraggableIfNecessary(self.target, params.draggable, params.dragOptions);
// resizing (using the jquery.ba-resize plugin). todo: decide
// whether to include or not.
if (this.source.resize) {
this.source.resize(function(e) {
jsPlumb.repaint(self.sourceId);
});
}
// just to make sure the UI gets initialised fully on all browsers.
self.repaint();
};
/*
* Class: Endpoint
*
* Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
* to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
* actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
* do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
* 'target' Endpoints for Connections.
*
*
*/
/*
* Function: Endpoint
*
* Endpoint constructor.
*
* Parameters:
* anchor - definition of the Anchor for the endpoint. You can include one or more Anchor definitions here; if you include more than one, jsPlumb creates a 'dynamic' Anchor, ie. an Anchor which changes position relative to the other elements in a Connection. Each Anchor definition can be either a string nominating one of the basic Anchors provided by jsPlumb (eg. "TopCenter"), or a four element array that designates the Anchor's location and orientation (eg, and this is equivalent to TopCenter, [ 0.5, 0, 0, -1 ]). To provide more than one Anchor definition just put them all in an array. You can mix string definitions with array definitions.
* endpoint - optional Endpoint definition. This takes the form of either a string nominating one of the basic Endpoints provided by jsPlumb (eg. "Rectangle"), or an array containing [name,params] for those cases where you don't wish to use the default values, eg. [ "Rectangle", { width:5, height:10 } ].
* paintStyle - endpoint style, a js object. may be null.
* hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
* source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
* canvas - canvas element to use. may be, and most often is, null.
* container - optional id or selector instructing jsPlumb where to attach the element it creates for this endpoint. you should read the documentation for a full discussion of this.
* connections - optional list of Connections to configure the Endpoint with.
* isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
* maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
* dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
* connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
* connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
* connector - optional Connector type to use. Like 'endpoint', this may be either a single string nominating a known Connector type (eg. "Bezier", "Straight"), or an array containing [name, params], eg. [ "Bezier", { curviness:160 } ].
* connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
* isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
* dropOptions - if isTarget is set to true, you can supply arguments for the underlying library's drop method with this parameter. Optional; defaults to null.
* reattach - optional boolean that determines whether or not the Connections reattach after they have been dragged off an Endpoint and left floating. defaults to false: Connections dropped in this way will just be deleted.
*/
var Endpoint = function(params) {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
params = params || {};
var self = this;
// ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
/*
* Function: bind
* Bind to an event on the Endpoint.
*
* Parameters:
* event - the event to bind. Available events on an Endpoint are:
* - *click* : notification that a Endpoint was clicked.
* - *dblclick* : notification that a Endpoint was double clicked.
* - *mouseenter* : notification that the mouse is over a Endpoint.
* - *mouseexit* : notification that the mouse exited a Endpoint.
*
* callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
*/
/*
* Function: setPaintStyle
* Sets the Endpoint's paint style and then repaints the Endpoint.
*
* Parameters:
* style - Style to use.
*/
/*
* Function: setHoverPaintStyle
* Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
* The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
* it. This is because people will most likely want to change just one thing when hovering, say the
* color for example, but leave the rest of the appearance the same.
*
* Parameters:
* style - Style to use when the mouse is hovering.
* doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
*/
/*
* Function: setHover
* Sets/unsets the hover state of this Endpoint.
*
* Parameters:
* hover - hover state boolean
* ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
*/
// ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
var visible = true;
/*
Function: isVisible
Returns whether or not the Endpoint is currently visible.
*/
this.isVisible = function() { return visible; };
/*
Function: setVisible
Sets whether or not the Endpoint is currently visible.
Parameters:
visible - whether or not the Endpoint should be visible.
doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
*/
this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
visible = v;
if (self.canvas) self.canvas.style.display = v ? "block" : "none";
if (!doNotChangeConnections) {
for (var i = 0; i < self.connections.length; i++) {
self.connections[i].setVisible(v);
if (!doNotNotifyOtherEndpoint) {
var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
// only change the other endpoint if this is its only connection.
if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
}
}
}
};
var id = new String('_jsplumb_e_' + (new Date()).getTime());
this.getId = function() { return id; };
if (params.dynamicAnchors)
self.anchor = new DynamicAnchor(jsPlumb.makeAnchors(params.dynamicAnchors));
else
self.anchor = params.anchor ? jsPlumb.makeAnchor(params.anchor) : params.anchors ? jsPlumb.makeAnchor(params.anchors) : jsPlumb.makeAnchor("TopCenter");
var _endpoint = params.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot",
endpointArgs = { _jsPlumb:self._jsPlumb, parent:params.parent, container:params.container };
if (_endpoint.constructor == String)
_endpoint = new jsPlumb.Endpoints[renderMode][_endpoint](endpointArgs);
else if (_endpoint.constructor == Array) {
endpointArgs = jsPlumb.extend(_endpoint[1], endpointArgs);
_endpoint = new jsPlumb.Endpoints[renderMode][_endpoint[0]](endpointArgs);
}
else
_endpoint = _endpoint.clone();
// assign a clone function using our derived endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
// and the clone is left in its place while the original one goes off on a magical journey.
this.clone = function() {
var o = new Object();
_endpoint.constructor.apply(o, [endpointArgs]);
return o;
};
self.endpoint = _endpoint;
self.type = self.endpoint.type;
// TODO this event listener registration code is identical to what Connection does: it should be refactored.
this.endpoint.bind("click", function(e) { self.fire("click", self, e); });
this.endpoint.bind("dblclick", function(e) { self.fire("dblclick", self, e); });
this.endpoint.bind("mouseenter", function(con, e) {
if (!self.isHover()) {
self.setHover(true);
self.fire("mouseenter", self, e);
}
});
this.endpoint.bind("mouseexit", function(con, e) {
if (self.isHover()) {
self.setHover(false);
self.fire("mouseexit", self, e);
}
});
// TODO this event listener registration code above is identical to what Connection does: it should be refactored.
this.setPaintStyle(params.paintStyle ||
params.style ||
_currentInstance.Defaults.EndpointStyle ||
jsPlumb.Defaults.EndpointStyle, true);
this.setHoverPaintStyle(params.hoverPaintStyle ||
_currentInstance.Defaults.EndpointHoverStyle ||
jsPlumb.Defaults.EndpointHoverStyle, true);
this.paintStyleInUse = this.paintStyle;
this.connectorStyle = params.connectorStyle;
this.connectorHoverStyle = params.connectorHoverStyle;
this.connectorOverlays = params.connectorOverlays;
this.connector = params.connector;
this.parent = params.parent;
this.isSource = params.isSource || false;
this.isTarget = params.isTarget || false;
var _element = params.source,
_uuid = params.uuid,
floatingEndpoint = null,
inPlaceCopy = null;
if (_uuid) endpointsByUUID[_uuid] = self;
var _elementId = _getAttribute(_element, "id");
this.elementId = _elementId;
this.element = _element;
var _maxConnections = params.maxConnections || _currentInstance.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
this.getAttachedElements = function() {
return self.connections;
};
/*
* Property: canvas
* The Endpoint's Canvas.
*/
this.canvas = this.endpoint.canvas;
/*
* Property: connections
* List of Connections this Endpoint is attached to.
*/
this.connections = params.connections || [];
/*
* Property: scope
* Scope descriptor for this Endpoint.
*/
this.scope = params.scope || DEFAULT_SCOPE;
this.timestamp = null;
var _reattach = params.reattach || false;
var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
this.computeAnchor = function(params) {
return self.anchor.compute(params);
};
/*
* Function: addConnection
* Adds a Connection to this Endpoint.
*
* Parameters:
* connection - the Connection to add.
*/
this.addConnection = function(connection) {
self.connections.push(connection);
};
/*
* Function: detach
* Detaches the given Connection from this Endpoint.
*
* Parameters:
* connection - the Connection to detach.
* ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
*/
this.detach = function(connection, ignoreTarget) {
var idx = _findIndex(self.connections, connection);
if (idx >= 0) {
self.connections.splice(idx, 1);
// this avoids a circular loop
if (!ignoreTarget) {
var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
t.detach(connection, true);
// check connection to see if we want to delete the other endpoint.
// if the user uses makeTarget to make some element a target for connections,
// it is possible that they will have set 'endpointToDeleteOnDetach': when
// you make a connection to an element that acts as a target (note: NOT an
// Endpoint; just some div as a target), Endpoints are created for that
// connection. so if you then delete that Connection, it is feasible you
// will want these auto-generated endpoints to be removed.
if (connection.endpointToDeleteOnDetach && connection.endpointToDeleteOnDetach.connections.length == 0)
jsPlumb.deleteEndpoint(connection.endpointToDeleteOnDetach);
}
_removeElements(connection.connector.getDisplayElements(), connection.parent);
_removeFromList(connectionsByScope, connection.scope, connection);
if(!ignoreTarget) fireDetachEvent(connection);
}
};
/*
* Function: detachAll
* Detaches all Connections this Endpoint has.
*/
this.detachAll = function() {
while (self.connections.length > 0) {
self.detach(self.connections[0]);
}
};
/*
* Function: detachFrom
* Removes any connections from this Endpoint that are connected to the given target endpoint.
*
* Parameters:
* targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
*/
this.detachFrom = function(targetEndpoint) {
var c = [];
for ( var i = 0; i < self.connections.length; i++) {
if (self.connections[i].endpoints[1] == targetEndpoint
|| self.connections[i].endpoints[0] == targetEndpoint) {
c.push(self.connections[i]);
}
}
for ( var i = 0; i < c.length; i++) {
c[i].setHover(false);
self.detach(c[i]);
}
};
/*
* Function: detachFromConnection
* Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
*
* Parameters:
* connection - Connection to detach from.
*/
this.detachFromConnection = function(connection) {
var idx = _findIndex(self.connections, connection);
if (idx >= 0) {
self.connections.splice(idx, 1);
}
};
/*
* Function: getElement
* Returns the DOM element this Endpoint is attached to.
*/
this.getElement = function() {
return _element;
};
/*
* Function: getUuid
* Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
*/
this.getUuid = function() {
return _uuid;
};
/**
* private but must be exposed.
*/
this.makeInPlaceCopy = function() {
return _newEndpoint( { anchor : self.anchor, source : _element, paintStyle : this.paintStyle, endpoint : _endpoint });
};
/*
* Function: isConnectedTo
* Returns whether or not this endpoint is connected to the given Endpoint.
*
* Parameters:
* endpoint - Endpoint to test.
*/
this.isConnectedTo = function(endpoint) {
var found = false;
if (endpoint) {
for ( var i = 0; i < self.connections.length; i++) {
if (self.connections[i].endpoints[1] == endpoint) {
found = true;
break;
}
}
}
return found;
};
/**
* private but needs to be exposed.
*/
this.isFloating = function() {
return floatingEndpoint != null;
};
/**
* returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
*/
this.connectorSelector = function() {
return (self.connections.length < _maxConnections) || _maxConnections == -1 ? null : self.connections[0];
};
/*
* Function: isFull
* Returns whether or not the Endpoint can accept any more Connections.
*/
this.isFull = function() {
return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
};
/*
* Function: setDragAllowedWhenFull
* Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
* which you're going to provide some other way of breaking connections, if you need to break them at all. This property
* is by default true; use it in conjunction with the 'reattach' option on a connect call.
*
* Parameters:
* allowed - whether drag is allowed or not when the Endpoint is full.
*/
this.setDragAllowedWhenFull = function(allowed) {
dragAllowedWhenFull = allowed;
};
/*
* Function: setStyle
* Sets the paint style of the Endpoint. This is a JS object of the same form you supply to a jsPlumb.addEndpoint or jsPlumb.connect call.
* TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
* setStyle and deprecate it if so.
*
* Parameters:
* style - Style object to set, for example {fillStyle:"blue"}.
*
* @deprecated use setPaintStyle instead.
*/
this.setStyle = self.setPaintStyle;
/**
* a deep equals check. everything must match, including the anchor,
* styles, everything. TODO: finish Endpoint.equals
*/
this.equals = function(endpoint) {
return this.anchor.equals(endpoint.anchor);
};
// a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
// or no connection to it is found, we return the first connection in our list.
var findConnectionToUseForDynamicAnchor = function(elementWithPrecedence) {
var idx = 0;
if (elementWithPrecedence != null) {
for (var i = 0; i < self.connections.length; i++) {
if (self.connections[i].sourceId == elementWithPrecedence || self.connections[i].targetId == elementWithPrecedence) {
idx = i;
break;
}
}
}
return self.connections[idx];
};
/*
* Function: paint
* Paints the Endpoint, recalculating offset and anchor positions if necessary.
*
* Parameters:
* timestamp - optional timestamp advising the Endpoint of the current paint time; if it has painted already once for this timestamp, it will not paint again.
* canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
* connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
*/
this.paint = function(params) {
params = params || {};
var timestamp = params.timestamp;
if (!timestamp || self.timestamp !== timestamp) {
var ap = params.anchorPoint, canvas = params.canvas, connectorPaintStyle = params.connectorPaintStyle;
if (ap == null) {
var xy = params.offset || offsets[_elementId];
var wh = params.dimensions || sizes[_elementId];
if (xy == null || wh == null) {
_updateOffset( { elId : _elementId, timestamp : timestamp });
xy = offsets[_elementId];
wh = sizes[_elementId];
}
var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
if (self.anchor.isDynamic) {
if (self.connections.length > 0) {
//var c = self.connections[0];
var c = findConnectionToUseForDynamicAnchor(params.elementWithPrecedence);
var oIdx = c.endpoints[0] == self ? 1 : 0;
var oId = oIdx == 0 ? c.sourceId : c.targetId;
var oOffset = offsets[oId], oWH = sizes[oId];
anchorParams.txy = [ oOffset.left, oOffset.top ];
anchorParams.twh = oWH;
anchorParams.tElement = c.endpoints[oIdx];
}
}
ap = self.anchor.compute(anchorParams);
}
var d = _endpoint.compute(ap, self.anchor.getOrientation(), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
_endpoint.paint(d, self.paintStyleInUse, self.anchor);
self.timestamp = timestamp;
}
};
this.repaint = this.paint;
/**
* @deprecated
*/
this.removeConnection = this.detach; // backwards compatibility
// is this a connection source? we make it draggable and have the
// drag listener maintain a connection with a floating endpoint.
if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
var start = function() {
jpc = self.connectorSelector();
if (self.isFull() && !dragAllowedWhenFull) return false;
_updateOffset( { elId : _elementId });
inPlaceCopy = self.makeInPlaceCopy();
inPlaceCopy.paint();
n = document.createElement("div");
n.style.position = "absolute";
var nE = _getElementObject(n);
_appendElement(n, self.parent);
// create and assign an id, and initialize the offset.
var id = _getId(nE);
// set the offset of this div to be where 'inPlaceCopy' is, to start with.
var ipcoel = _getElementObject(inPlaceCopy.canvas),
ipco = jsPlumb.CurrentLibrary.getOffset(ipcoel),
po = inPlaceCopy.canvas.offsetParent != null ?
inPlaceCopy.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(inPlaceCopy.canvas.offsetParent)
: { left:0, top: 0};
jsPlumb.CurrentLibrary.setOffset(n, {left:ipco.left - po.left, top:ipco.top-po.top});
_updateOffset( { elId : id });
// store the id of the dragging div and the source element. the drop function will pick these up.
_setAttribute(_getElementObject(self.canvas), "dragId", id);
_setAttribute(_getElementObject(self.canvas), "elId", _elementId);
// create a floating anchor
var floatingAnchor = new FloatingAnchor( { reference : self.anchor, referenceCanvas : self.canvas });
floatingEndpoint = _newEndpoint({ paintStyle : self.paintStyle, endpoint : _endpoint, anchor : floatingAnchor, source : nE });
if (jpc == null) {
self.anchor.locked = true;
// create a connection. one end is this endpoint, the
// other is a floating endpoint.
jpc = _newConnection({
sourceEndpoint : self,
targetEndpoint : floatingEndpoint,
source : _getElementObject(_element),
target : _getElementObject(n),
anchors : [ self.anchor, floatingAnchor ],
paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
hoverPaintStyle:params.connectorHoverStyle,
connector : params.connector, // this can also be null. Connection will use the default.
overlays : params.connectorOverlays
});
// TODO determine whether or not we wish to do de-select hover when dragging a connection.
// it may be the case that we actually want to set it, since it provides a good
// visual cue.
jpc.connector.setHover(false);
} else {
existingJpc = true;
// TODO determine whether or not we wish to do de-select hover when dragging a connection.
// it may be the case that we actually want to set it, since it provides a good
// visual cue.
jpc.connector.setHover(false);
// if existing connection, allow to be dropped back on the source endpoint (issue 51).
_initDropTarget(_getElementObject(inPlaceCopy.canvas));
var anchorIdx = jpc.sourceId == _elementId ? 0 : 1; // are we the source or the target?
jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
// store the original scope (issue 57)
var c = _getElementObject(self.canvas);
var dragScope = jsPlumb.CurrentLibrary.getDragScope(c);
_setAttribute(c, "originalScope", dragScope);
// now we want to get this endpoint's DROP scope, and set it for now: we can only be dropped on drop zones
// that have our drop scope (issue 57).
var dropScope = jsPlumb.CurrentLibrary.getDropScope(c);//jpc.endpoints[anchorIdx == 0 ? 1 : 0].getDropScope();
jsPlumb.CurrentLibrary.setDragScope(c, dropScope);
// now we replace ourselves with the temporary div we created above:
if (anchorIdx == 0) {
existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
jpc.source = _getElementObject(n);
jpc.sourceId = id;
} else {
existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
jpc.target = _getElementObject(n);
jpc.targetId = id;
}
// lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
// store the original endpoint and assign the new floating endpoint for the drag.
jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
jpc.endpoints[anchorIdx] = floatingEndpoint;
}
// register it and register connection on it.
floatingConnections[id] = jpc;
floatingEndpoint.addConnection(jpc);
// only register for the target endpoint; we will not be dragging the source at any time
// before this connection is either discarded or made into a permanent connection.
_addToList(endpointsByElement, id, floatingEndpoint);
// tell jsplumb about it
_currentInstance.currentlyDragging = true;
};
var jpcl = jsPlumb.CurrentLibrary,
dragOptions = params.dragOptions || {},
defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
startEvent = jpcl.dragEvents['start'],
stopEvent = jpcl.dragEvents['stop'],
dragEvent = jpcl.dragEvents['drag'];
dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
dragOptions.scope = dragOptions.scope || self.scope;
dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
dragOptions[dragEvent] = _wrap(dragOptions[dragEvent],
function() {
var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
jsPlumb.CurrentLibrary.setOffset(n, _ui);
_draw(_getElementObject(n), _ui);
});
dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
function() {
_removeFromList(endpointsByElement, id, floatingEndpoint);
_removeElements( [ n, floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
_removeElement(inPlaceCopy.canvas, _element);
var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
if (jpc.endpoints[idx] == floatingEndpoint) {
// if the connection was an existing one:
if (existingJpc && jpc.suspendedEndpoint) {
// fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
// floating endpoint has been replaced.
if (idx == 0) {
jpc.source = existingJpcParams[0];
jpc.sourceId = existingJpcParams[1];
} else {
jpc.target = existingJpcParams[0];
jpc.targetId = existingJpcParams[1];
}
// restore the original scope (issue 57)
jsPlumb.CurrentLibrary.setDragScope(existingJpcParams[2], existingJpcParams[3]);
jpc.endpoints[idx] = jpc.suspendedEndpoint;
if (_reattach) {
jpc.floatingAnchorIndex = null;
jpc.suspendedEndpoint.addConnection(jpc);
jsPlumb.repaint(existingJpcParams[1]);
} else {
jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc); // the main endpoint will inform the floating endpoint
// to disconnect, and also post the detached event.
}
} else {
// TODO this looks suspiciously kind of like an Endpoint.detach call too.
// i wonder if this one should post an event though. maybe this is good like this.
_removeElements(jpc.connector.getDisplayElements(), self.parent);
self.detachFromConnection(jpc);
}
}
self.anchor.locked = false;
self.paint();
jpc.setHover(false);
jpc.repaint();
jpc = null;
delete inPlaceCopy;
delete endpointsByElement[floatingEndpoint.elementId];
floatingEndpoint = null;
delete floatingEndpoint;
_currentInstance.currentlyDragging = false;
});
var i = _getElementObject(self.canvas);
jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
}
// pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
// back onto the endpoint you detached it from.
var _initDropTarget = function(canvas) {
if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
dropOptions = jsPlumb.extend( {}, dropOptions);
dropOptions.scope = dropOptions.scope || self.scope;
var originalAnchor = null;
var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
var drop = function() {
var draggable = _getElementObject(jsPlumb.CurrentLibrary.getDragObject(arguments));
var id = _getAttribute(draggable, "dragId");
var elId = _getAttribute(draggable, "elId");
// restore the original scope if necessary (issue 57)
var scope = _getAttribute(draggable, "originalScope");
if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
var jpc = floatingConnections[id];
var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
if (idx == 0) {
jpc.source = _element;
jpc.sourceId = _elementId;
} else {
jpc.target = _element;
jpc.targetId = _elementId;
}
// todo test that the target is not full.
// remove this jpc from the current endpoint
jpc.endpoints[idx].detachFromConnection(jpc);
if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
jpc.endpoints[idx] = self;
self.addConnection(jpc);
if (!jpc.suspendedEndpoint) {
_addToList(connectionsByScope, jpc.scope, jpc);
_initDraggableIfNecessary(_element, params.draggable, {});
}
else {
var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
// fire a detach event
_currentInstance.fire("jsPlumbConnectionDetached", {
source : idx == 0 ? suspendedElement : jpc.source,
target : idx == 1 ? suspendedElement : jpc.target,
sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
targetId : idx == 1 ? suspendedElementId : jpc.targetId,
sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
connection : jpc
});
}
jsPlumb.repaint(elId);
_currentInstance.fire("jsPlumbConnection", {
source : jpc.source, target : jpc.target,
sourceId : jpc.sourceId, targetId : jpc.targetId,
sourceEndpoint : jpc.endpoints[0],
targetEndpoint : jpc.endpoints[1],
connection:jpc
});
}
_currentInstance.currentlyDragging = false;
delete floatingConnections[id];
};
dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], drop);
dropOptions[overEvent] = _wrap(dropOptions[overEvent],
function() {
var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
var id = _getAttribute( _getElementObject(draggable), "dragId");
var jpc = floatingConnections[id];
if (jpc != null) {
var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
jpc.endpoints[idx].anchor.over(self.anchor);
}
});
dropOptions[outEvent] = _wrap(dropOptions[outEvent],
function() {
var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
id = _getAttribute(_getElementObject(draggable), "dragId"),
jpc = floatingConnections[id];
if (jpc != null) {
var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
jpc.endpoints[idx].anchor.out();
}
});
jsPlumb.CurrentLibrary.initDroppable(canvas, dropOptions);
}
};
// initialise the endpoint's canvas as a drop target. this will be ignored if the endpoint is not a target or drag is not supported.
_initDropTarget(_getElementObject(self.canvas));
return self;
};
};
var jsPlumb = window.jsPlumb = new jsPlumbInstance();
jsPlumb.getInstance = function(_defaults) {
var j = new jsPlumbInstance(_defaults);
j.init();
return j;
};
var _curryAnchor = function(x,y,ox,oy) {
return function() {
return jsPlumb.makeAnchor(x,y,ox,oy);
};
};
jsPlumb.Anchors["TopCenter"] = _curryAnchor(0.5, 0, 0,-1);
jsPlumb.Anchors["BottomCenter"] = _curryAnchor(0.5, 1, 0, 1);
jsPlumb.Anchors["LeftMiddle"] = _curryAnchor(0, 0.5, -1, 0);
jsPlumb.Anchors["RightMiddle"] = _curryAnchor(1, 0.5, 1, 0);
jsPlumb.Anchors["Center"] = _curryAnchor(0.5, 0.5, 0, 0);
jsPlumb.Anchors["TopRight"] = _curryAnchor(1, 0, 0,-1);
jsPlumb.Anchors["BottomRight"] = _curryAnchor(1, 1, 0, 1);
jsPlumb.Anchors["TopLeft"] = _curryAnchor(0, 0, 0, -1);
jsPlumb.Anchors["BottomLeft"] = _curryAnchor(0, 1, 0, 1);
jsPlumb.Defaults.DynamicAnchors = function() {
return jsPlumb.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"]);
};
jsPlumb.Anchors["AutoDefault"] = function() { return jsPlumb.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors()); };
})();
/*
* jsPlumb
*
* Title:jsPlumb 1.3.2
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the default Connectors, Endpoint and Overlay definitions.
*
* Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://code.google.com/p/jsplumb
*
* Triple licensed under the MIT, GPL2 and Beer licenses.
*/
(function() {
/**
*
* Helper class to consume unused mouse events by components that are DOM elements and
* are used by all of the different rendering modes.
*
*/
jsPlumb.DOMElementComponent = function(params) {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
// when render mode is canvas, these functions may be called by the canvas mouse handler.
// this component is safe to pipe this stuff to /dev/null.
this.mousemove =
this.dblclick =
this.click =
this.mousedown =
this.mouseup = function(e) { };
};
/**
* Class: Connectors.Straight
* The Straight connector draws a simple straight line between the two anchor points. It does not have any constructor parameters.
*/
jsPlumb.Connectors.Straight = function() {
this.type = "Straight";
var self = this;
var currentPoints = null;
var _m, _m2, _b, _dx, _dy, _theta, _theta2, _sx, _sy, _tx, _ty;
/**
* Computes the new size and position of the canvas.
* @param sourceAnchor Absolute position on screen of the source object's anchor.
* @param targetAnchor Absolute position on screen of the target object's anchor.
* @param positionMatrix Indicates the relative positions of the left,top of the
* two plumbed objects. so [0,0] indicates that the source is to the left of, and
* above, the target. [1,0] means the source is to the right and above. [0,1] means
* the source is to the left and below. [1,1] means the source is to the right
* and below. this is used to figure out which direction to draw the connector in.
* @returns an array of positioning information. the first two values are
* the [left, top] absolute position the canvas should be placed on screen. the
* next two values are the [width,height] the canvas should be. after that each
* Connector can put whatever it likes into the array:it will be passed back in
* to the paint call. This particular function stores the origin and destination of
* the line it is going to draw. a more involved implementation, like a Bezier curve,
* would store the control point info in this array too.
*/
this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
var w = Math.abs(sourcePos[0] - targetPos[0]);
var h = Math.abs(sourcePos[1] - targetPos[1]);
var widthAdjusted = false, heightAdjusted = false;
// these are padding to ensure the whole connector line appears
var xo = 0.45 * w, yo = 0.45 * h;
// these are padding to ensure the whole connector line appears
w *= 1.9; h *=1.9;
var x = Math.min(sourcePos[0], targetPos[0]) - xo;
var y = Math.min(sourcePos[1], targetPos[1]) - yo;
// minimum size is 2 * line Width if minWidth was not given.
var calculatedMinWidth = Math.max(2 * lineWidth, minWidth);
if (w < calculatedMinWidth) {
w = calculatedMinWidth;
x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - (calculatedMinWidth / 2);
xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;
}
if (h < calculatedMinWidth) {
h = calculatedMinWidth;
y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - (calculatedMinWidth / 2);
yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;
}
_sx = sourcePos[0] < targetPos[0] ? xo : w-xo;
_sy = sourcePos[1] < targetPos[1] ? yo:h-yo;
_tx = sourcePos[0] < targetPos[0] ? w-xo : xo;
_ty = sourcePos[1] < targetPos[1] ? h-yo : yo;
currentPoints = [ x, y, w, h, _sx, _sy, _tx, _ty ];
_dx = _tx - _sx, _dy = (_ty - _sy);
_m = _dy / _dx, _m2 = -1 / _m;
_b = -1 * ((_m * _sx) - _sy);
_theta = Math.atan(_m); _theta2 = Math.atan(_m2);
return currentPoints;
};
/**
* returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
*/
this.pointOnPath = function(location) {
var xp = _sx + (location * _dx);
var yp = (_m == Infinity || _m == -Infinity) ? _sy + (location * (_ty - _sy)) : (_m * xp) + _b;
return {x:xp, y:yp};
};
/**
* returns the gradient of the connector at the given point - which for us is constant.
*/
this.gradientAtPoint = function(location) { return _m; };
/**
* returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
* 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
*/
this.pointAlongPathFrom = function(location, distance) {
var p = self.pointOnPath(location);
var orientation = distance > 0 ? 1 : -1;
var y = Math.abs(distance * Math.sin(_theta));
if (_sy > _ty) y = y * -1;
var x = Math.abs(distance * Math.cos(_theta));
if (_sx > _tx) x = x * -1;
return {x:p.x + (orientation * x), y:p.y + (orientation * y)};
};
/**
* calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
* the line is 'length' pixels long.
*/
this.perpendicularToPathAt = function(location, length, distance) {
var p = self.pointAlongPathFrom(location, distance);
var m = self.gradientAtPoint(p.location);
var _theta2 = Math.atan(-1 / m);
var y = length / 2 * Math.sin(_theta2);
var x = length / 2 * Math.cos(_theta2);
return [{x:p.x + x, y:p.y + y}, {x:p.x - x, y:p.y - y}];
};
};
/**
* Class:Connectors.Bezier
* This Connector draws a Bezier curve with two control points. You can provide a 'curviness' value which gets applied to jsPlumb's
* internal voodoo machine and ends up generating locations for the two control points. See the constructor documentation below.
*/
/**
* Function:Constructor
*
* Parameters:
* curviness - How 'curvy' you want the curve to be! This is a directive for the placement of control points, not endpoints of the curve, so your curve does not
* actually touch the given point, but it has the tendency to lean towards it. The larger this value, the greater the curve is pulled from a straight line.
* Optional; defaults to 150.
*
*/
jsPlumb.Connectors.Bezier = function(params) {
var self = this;
params = params || {};
this.majorAnchor = params.curviness || 150;
this.minorAnchor = 10;
var currentPoints = null;
this.type = "Bezier";
this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
// determine if the two anchors are perpendicular to each other in their orientation. we swap the control
// points around if so (code could be tightened up)
var soo = sourceAnchor.getOrientation(), too = targetAnchor.getOrientation();
var perpendicular = soo[0] != too[0] || soo[1] == too[1];
var p = [];
var ma = self.majorAnchor, mi = self.minorAnchor;
if (!perpendicular) {
if (soo[0] == 0) // X
p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
else p.push(point[0] - (ma * soo[0]));
if (soo[1] == 0) // Y
p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
else p.push(point[1] + (ma * too[1]));
}
else {
if (too[0] == 0) // X
p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
else p.push(point[0] + (ma * too[0]));
if (too[1] == 0) // Y
p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
else p.push(point[1] + (ma * soo[1]));
}
return p;
};
var _CP, _CP2, _sx, _tx, _ty, _sx, _sy, _canvasX, _canvasY, _w, _h;
this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth)
{
lineWidth = lineWidth || 0;
_w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth;
_h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
_canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2);
_canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
_sx = sourcePos[0] < targetPos[0] ? _w - (lineWidth/2): (lineWidth/2);
_sy = sourcePos[1] < targetPos[1] ? _h - (lineWidth/2) : (lineWidth/2);
_tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : _w - (lineWidth/2);
_ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : _h - (lineWidth/2);
_CP = self._findControlPoint([_sx,_sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
_CP2 = self._findControlPoint([_tx,_ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
var minx1 = Math.min(_sx,_tx); var minx2 = Math.min(_CP[0], _CP2[0]); var minx = Math.min(minx1,minx2);
var maxx1 = Math.max(_sx,_tx); var maxx2 = Math.max(_CP[0], _CP2[0]); var maxx = Math.max(maxx1,maxx2);
if (maxx > _w) _w = maxx;
if (minx < 0) {
_canvasX += minx; var ox = Math.abs(minx);
_w += ox; _CP[0] += ox; _sx += ox; _tx +=ox; _CP2[0] += ox;
}
var miny1 = Math.min(_sy,_ty); var miny2 = Math.min(_CP[1], _CP2[1]); var miny = Math.min(miny1,miny2);
var maxy1 = Math.max(_sy,_ty); var maxy2 = Math.max(_CP[1], _CP2[1]); var maxy = Math.max(maxy1,maxy2);
if (maxy > _h) _h = maxy;
if (miny < 0) {
_canvasY += miny; var oy = Math.abs(miny);
_h += oy; _CP[1] += oy; _sy += oy; _ty +=oy; _CP2[1] += oy;
}
if (minWidth && _w < minWidth) {
var posAdjust = (minWidth - _w) / 2;
_w = minWidth;
_canvasX -= posAdjust; _sx = _sx + posAdjust ; _tx = _tx + posAdjust; _CP[0] = _CP[0] + posAdjust; _CP2[0] = _CP2[0] + posAdjust;
}
if (minWidth && _h < minWidth) {
var posAdjust = (minWidth - _h) / 2;
_h = minWidth;
_canvasY -= posAdjust; _sy = _sy + posAdjust ; _ty = _ty + posAdjust; _CP[1] = _CP[1] + posAdjust; _CP2[1] = _CP2[1] + posAdjust;
}
currentPoints = [_canvasX, _canvasY, _w, _h, _sx, _sy, _tx, _ty, _CP[0], _CP[1], _CP2[0], _CP2[1] ];
return currentPoints;
};
var _makeCurve = function() {
return [
{ x:_sx, y:_sy },
{ x:_CP[0], y:_CP[1] },
{ x:_CP2[0], y:_CP2[1] },
{ x:_tx, y:_ty }
];
};
/**
* returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
*/
this.pointOnPath = function(location) {
return jsBezier.pointOnCurve(_makeCurve(), location);
};
/**
* returns the gradient of the connector at the given point.
*/
this.gradientAtPoint = function(location) {
return jsBezier.gradientAtPoint(_makeCurve(), location);
};
/**
* for Bezier curves this method is a little tricky, cos calculating path distance algebraically is notoriously difficult.
* this method is iterative, jumping forward .05% of the path at a time and summing the distance between this point and the previous
* one, until the sum reaches 'distance'. the method may turn out to be computationally expensive; we'll see.
* another drawback of this method is that if the connector gets quite long, .05% of the length of it is not necessarily smaller
* than the desired distance, in which case the loop returns immediately and the arrow is mis-shapen. so a better strategy might be to
* calculate the step as a function of distance/distance between endpoints.
*/
this.pointAlongPathFrom = function(location, distance) {
return jsBezier.pointAlongCurveFrom(_makeCurve(), location, distance);
};
/**
* calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
* the line is 'length' pixels long.
*/
this.perpendicularToPathAt = function(location, length, distance) {
return jsBezier.perpendicularToCurveAt(_makeCurve(), location, length, distance);
};
};
/**
* Class: Connectors.Flowchart
* Provides 'flowchart' connectors, consisting of vertical and horizontal line segments.
*/
/**
* Function: Constructor
*
* Parameters:
* stub - minimum length for the stub at each end of the connector. defaults to 30 pixels.
*/
jsPlumb.Connectors.Flowchart = function(params) {
this.type = "Flowchart";
params = params || {};
var self = this,
minStubLength = params.stub || params.minStubLength /* bwds compat. */ || 30,
segments = [],
segmentGradients = [],
segmentProportions = [],
segmentLengths = [],
segmentProportionalLengths = [],
points = [],
swapX,
swapY,
/**
* recalculates the gradients of each segment, and the points at which the segments begin, proportional to the total length travelled
* by all the segments that constitute the connector.
*/
updateSegmentGradientsAndProportions = function(startX, startY, endX, endY) {
var total = 0;
for (var i = 0; i < segments.length; i++) {
var sx = i == 0 ? startX : segments[i][2],
sy = i == 0 ? startY : segments[i][3],
ex = segments[i][0],
ey = segments[i][1];
segmentGradients[i] = sx == ex ? Infinity : 0;
segmentLengths[i] = Math.abs(sx == ex ? ey - sy : ex - sx);
total += segmentLengths[i];
}
var curLoc = 0;
for (var i = 0; i < segments.length; i++) {
segmentProportionalLengths[i] = segmentLengths[i] / total;
segmentProportions[i] = [curLoc, (curLoc += (segmentLengths[i] / total)) ];
}
},
appendSegmentsToPoints = function() {
points.push(segments.length);
for (var i = 0; i < segments.length; i++) {
points.push(segments[i][0]);
points.push(segments[i][1]);
}
},
/**
* helper method to add a segment.
*/
addSegment = function(x, y, sx, sy, tx, ty) {
var lx = segments.length == 0 ? sx : segments[segments.length - 1][0];
var ly = segments.length == 0 ? sy : segments[segments.length - 1][1];
segments.push([x, y, lx, ly]);
},
/**
* returns [segment, proportion of travel in segment, segment index] for the segment
* that contains the point which is 'location' distance along the entire path, where
* 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
* are made up of a list of segments, each of which contributes some fraction to
* the total length.
*/
findSegmentForLocation = function(location) {
var idx = segmentProportions.length - 1, inSegmentProportion = 0;
for (var i = 0; i < segmentProportions.length; i++) {
if (segmentProportions[i][1] >= location) {
idx = i;
inSegmentProportion = (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
break;
}
}
return { segment:segments[idx], proportion:inSegmentProportion, index:idx };
};
this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
segments = [];
segmentGradients = [];
segmentProportionalLengths = [];
segmentLengths = [];
segmentProportionals = [];
swapX = targetPos[0] < sourcePos[0];
swapY = targetPos[1] < sourcePos[1];
var lw = lineWidth || 1,
offx = (lw / 2) + (minStubLength * 2),
offy = (lw / 2) + (minStubLength * 2),
so = sourceAnchor.orientation || sourceAnchor.getOrientation(),
to = targetAnchor.orientation || targetAnchor.getOrientation(),
x = swapX ? targetPos[0] : sourcePos[0],
y = swapY ? targetPos[1] : sourcePos[1],
w = Math.abs(targetPos[0] - sourcePos[0]) + 2*offx,
h = Math.abs(targetPos[1] - sourcePos[1]) + 2*offy;
if (w < minWidth) {
offx += (minWidth - w) / 2;
w = minWidth;
}
if (h < minWidth) {
offy += (minWidth - h) / 2;
h = minWidth;
}
var sx = swapX ? w-offx : offx,
sy = swapY ? h-offy : offy,
tx = swapX ? offx : w-offx ,
ty = swapY ? offy : h-offy,
startStubX = sx + (so[0] * minStubLength),
startStubY = sy + (so[1] * minStubLength),
endStubX = tx + (to[0] * minStubLength),
endStubY = ty + (to[1] * minStubLength),
midx = startStubX + ((endStubX - startStubX) / 2),
midy = startStubY + ((endStubY - startStubY) / 2);
x -= offx; y -= offy;
points = [x, y, w, h, sx, sy, tx, ty], extraPoints = [];
addSegment(startStubX, startStubY, sx, sy, tx, ty);
if (so[0] == 0) {
var startStubIsBeforeEndStub = startStubY < endStubY;
// when start point's stub is less than endpoint's stub
if (startStubIsBeforeEndStub) {
addSegment(startStubX, midy, sx, sy, tx, ty);
addSegment(midx, midy, sx, sy, tx, ty);
addSegment(endStubX, midy, sx, sy, tx, ty);
} else {
// when start point's stub is greater than endpoint's stub
addSegment(midx, startStubY, sx, sy, tx, ty);
addSegment(midx, endStubY, sx, sy, tx, ty);
}
}
else {
var startStubIsBeforeEndStub = startStubX < endStubX;
// when start point's stub is less than endpoint's stub
if (startStubIsBeforeEndStub) {
addSegment(midx, startStubY, sx, sy, tx, ty);
addSegment(midx, midy, sx, sy, tx, ty);
addSegment(midx, endStubY, sx, sy, tx, ty);
} else {
// when start point's stub is greater than endpoint's stub
addSegment(startStubX, midy, sx, sy, tx, ty);
addSegment(endStubX, midy, sx, sy, tx, ty);
}
}
addSegment(endStubX, endStubY, sx, sy, tx, ty);
addSegment(tx, ty, sx, sy, tx, ty);
appendSegmentsToPoints();
updateSegmentGradientsAndProportions(sx, sy, tx, ty);
return points;
};
/**
* returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive. for this connector we must first figure out which segment the given point lies in, and then compute the x,y position
* from our knowledge of the segment's start and end points.
*/
this.pointOnPath = function(location) {
return self.pointAlongPathFrom(location, 0);
};
/**
* returns the gradient of the connector at the given point; the gradient will be either 0 or Infinity, depending on the direction of the
* segment the point falls in. segment gradients are calculated in the compute method.
*/
this.gradientAtPoint = function(location) {
return segmentGradients[findSegmentForLocation(location)["index"]];
};
/**
* returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
* 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels. when you consider this concept from the point of view
* of this connector, it starts to become clear that there's a problem with the overlay paint code: given that this connector makes several
* 90 degree turns, it's entirely possible that an arrow overlay could be forced to paint itself around a corner, which would look stupid. this is
* because jsPlumb uses this method (and pointOnPath) so determine the locations of the various points that go to make up an overlay. a better
* solution would probably be to just use pointOnPath along with gradientAtPoint, and draw the overlay so that its axis ran along
* a tangent to the connector. for straight line connectors this would obviously mean the overlay was painted directly on the connector, since a
* tangent to a straight line is the line itself, which is what we want; for this connector, and for beziers, the results would probably be better. an additional
* advantage is, of course, that there's less computation involved doing it that way.
*/
this.pointAlongPathFrom = function(location, distance) {
var s = findSegmentForLocation(location), seg = s.segment, p = s.proportion, sl = segmentLengths[s.index], m = segmentGradients[s.index];
var e = {
x : m == Infinity ? seg[2] : seg[2] > seg[0] ? seg[0] + ((1 - p) * sl) - distance : seg[2] + (p * sl) + distance,
y : m == 0 ? seg[3] : seg[3] > seg[1] ? seg[1] + ((1 - p) * sl) - distance : seg[3] + (p * sl) + distance,
segmentInfo : s
};
return e;
};
/**
* calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
* the line is 'length' pixels long.
*/
this.perpendicularToPathAt = function(location, length, distance) {
var p = self.pointAlongPathFrom(location, distance);
var m = segmentGradients[p.segmentInfo.index];
var _theta2 = Math.atan(-1 / m);
var y = length / 2 * Math.sin(_theta2);
var x = length / 2 * Math.cos(_theta2);
return [{x:p.x + x, y:p.y + y}, {x:p.x - x, y:p.y - y}];
};
};
// ********************************* END OF CONNECTOR TYPES *******************************************************************
// ********************************* ENDPOINT TYPES *******************************************************************
/**
* Class: Endpoints.Dot
* A round endpoint, with default radius 10 pixels.
*/
/**
* Function: Constructor
*
* Parameters:
*
* radius - radius of the endpoint. defaults to 10 pixels.
*/
jsPlumb.Endpoints.Dot = function(params) {
this.type = "Dot";
var self = this;
params = params || {};
this.radius = params.radius || 10;
this.defaultOffset = 0.5 * this.radius;
this.defaultInnerRadius = this.radius / 3;
this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var r = endpointStyle.radius || self.radius;
var x = anchorPoint[0] - r;
var y = anchorPoint[1] - r;
return [ x, y, r * 2, r * 2, r ];
};
};
/**
* Class: Endpoints.Rectangle
* A Rectangular Endpoint, with default size 20x20.
*/
/**
* Function: Constructor
*
* Parameters:
*
* width - width of the endpoint. defaults to 20 pixels.
* height - height of the endpoint. defaults to 20 pixels.
*/
jsPlumb.Endpoints.Rectangle = function(params) {
this.type = "Rectangle";
var self = this;
params = params || {};
this.width = params.width || 20;
this.height = params.height || 20;
this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var width = endpointStyle.width || self.width;
var height = endpointStyle.height || self.height;
var x = anchorPoint[0] - (width/2);
var y = anchorPoint[1] - (height/2);
return [ x, y, width, height];
};
};
/**
* Class: Endpoints.Image
* Draws an image as the Endpoint.
*/
/**
* Function: Constructor
*
* Parameters:
*
* src - location of the image to use.
*/
jsPlumb.Endpoints.Image = function(params) {
this.type = "Image";
jsPlumb.DOMElementComponent.apply(this, arguments);
var self = this, initialized = false;
this.img = new Image();
self.ready = false;
this.img.onload = function() {
self.ready = true;
};
this.img.src = params.src || params.url;
this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
self.anchorPoint = anchorPoint;
if (self.ready) return [anchorPoint[0] - self.img.width / 2, anchorPoint[1] - self.img.height/ 2, self.img.width, self.img.height];
else return [0,0,0,0];
};
self.canvas = document.createElement("img"), initialized = false;
self.canvas.style["margin"] = 0;
self.canvas.style["padding"] = 0;
self.canvas.style["outline"] = 0;
self.canvas.style["position"] = "absolute";
self.canvas.className = jsPlumb.endpointClass;
jsPlumb.appendElement(self.canvas, params.parent);
self.attachListeners(self.canvas, self);
var actuallyPaint = function(d, style, anchor) {
if (!initialized) {
self.canvas.setAttribute("src", self.img.src);
initialized = true;
}
var width = self.img.width,
height = self.img.height,
x = self.anchorPoint[0] - (width/2),
y = self.anchorPoint[1] - (height/2);
jsPlumb.sizeCanvas(self.canvas, x, y, width, height);
};
this.paint = function(d, style, anchor) {
if (self.ready) {
actuallyPaint(d, style, anchor);
}
else {
window.setTimeout(function() {
self.paint(d, style, anchor);
}, 200);
}
};
};
/**
* Class: Endpoints.Blank
* An Endpoint that paints nothing on the screen, and cannot be interacted with using the mouse. There are no constructor parameters for this Endpoint.
*/
jsPlumb.Endpoints.Blank = function(params) {
var self = this;
this.type = "Blank";
jsPlumb.DOMElementComponent.apply(this, arguments);
this.compute = function() {
return [0,0,10,0];
};
self.canvas = document.createElement("div");
self.canvas.style.display = "block";
self.canvas.style.width = "1px";
self.canvas.style.height = "1px";
self.canvas.style.background = "transparent";
self.canvas.style.position = "absolute";
jsPlumb.appendElement(self.canvas, params.parent);
this.paint = function() { };
};
/**
* Class: Endpoints.Triangle
* A triangular Endpoint.
*/
/**
* Function: Constructor
*
* Parameters:
*
* width - width of the triangle's base. defaults to 55 pixels.
* height - height of the triangle from base to apex. defaults to 55 pixels.
*/
jsPlumb.Endpoints.Triangle = function(params) {
this.type = "Triangle";
params = params || { };
params.width = params.width || 55;
param.height = params.height || 55;
this.width = params.width;
this.height = params.height;
this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var width = endpointStyle.width || self.width;
var height = endpointStyle.height || self.height;
var x = anchorPoint[0] - (width/2);
var y = anchorPoint[1] - (height/2);
return [ x, y, width, height ];
};
};
// ********************************* END OF ENDPOINT TYPES *******************************************************************
// ********************************* OVERLAY DEFINITIONS ***********************************************************************
/**
* Class: Overlays.Arrow
*
* An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length
* of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
* of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line
* across the tail.
*/
/**
* Function: Constructor
*
* Parameters:
*
* length - distance in pixels from head to tail baseline. default 20.
* width - width in pixels of the tail baseline. default 20.
* fillStyle - style to use when filling the arrow. defaults to "black".
* strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
* lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null.
* foldback - distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
* direction - indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
*/
jsPlumb.Overlays.Arrow = function(params) {
this.type = "Arrow";
params = params || {};
var self = this;
this.length = params.length || 20;
this.width = params.width || 20;
this.id = params.id;
this.connection = params.connection;
var direction = (params.direction || 1) < 0 ? -1 : 1;
var paintStyle = params.paintStyle || { lineWidth:1 };
this.loc = params.location == null ? 0.5 : params.location;
// how far along the arrow the lines folding back in come to. default is 62.3%.
var foldback = params.foldback || 0.623;
var _getFoldBackPoint = function(connector, loc) {
if (foldback == 0.5) return connector.pointOnPath(loc);
else {
var adj = 0.5 - foldback; // we calculate relative to the center
return connector.pointAlongPathFrom(loc, direction * self.length * adj);
}
};
this.computeMaxSize = function() { return self.width * 1.5; };
this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
// this is the arrow head position
var hxy = connector.pointAlongPathFrom(self.loc, direction * (self.length / 2));
// this is the center of the tail
var txy = connector.pointAlongPathFrom(self.loc, -1 * direction * (self.length / 2)), tx = txy.x, ty = txy.y;
// this is the tail vector
var tail = connector.perpendicularToPathAt(self.loc, self.width, -1 * direction * (self.length / 2));
// this is the point the tail goes in to
var cxy = _getFoldBackPoint(connector, self.loc);
// if loc = 1, then hxy should be flush with the element, or if direction == -1, the tail midpoint.
if (self.loc == 1) {
var lxy = connector.pointOnPath(self.loc);
// TODO determine why the 1.2.6 released version does not
// use 'direction' in the two equations below, yet both
// that and 1.3.0 still paint the arrows correctly.
var dx = (lxy.x - hxy.x) * direction, dy = (lxy.y - hxy.y) * direction;
cxy.x += dx; cxy.y += dy;
txy.x += dx; txy.y += dy;
tail[0].x += dx; tail[0].y += dy;
tail[1].x += dx; tail[1].y += dy;
hxy.x += dx; hxy.y += dy;
}
// if loc = 0, then tail midpoint should be flush with the element, or, if direction == -1, hxy should be.
if (self.loc == 0) {
var lxy = connector.pointOnPath(self.loc);
var tailMid = foldback > 1 ? cxy : {
x:tail[0].x + ((tail[1].x - tail[0].x) / 2),
y:tail[0].y + ((tail[1].y - tail[0].y) / 2)
};
var dx = (lxy.x - tailMid.x) * direction, dy = (lxy.y - tailMid.y) * direction;
cxy.x += dx; cxy.y += dy;
txy.x += dx; txy.y += dy;
tail[0].x += dx; tail[0].y += dy;
tail[1].x += dx; tail[1].y += dy;
hxy.x += dx; hxy.y += dy;
}
var minx = Math.min(hxy.x, tail[0].x, tail[1].x);
var maxx = Math.max(hxy.x, tail[0].x, tail[1].x);
var miny = Math.min(hxy.y, tail[0].y, tail[1].y);
var maxy = Math.max(hxy.y, tail[0].y, tail[1].y);
var d = { hxy:hxy, tail:tail, cxy:cxy },
strokeStyle = paintStyle.strokeStyle || currentConnectionPaintStyle.strokeStyle,
fillStyle = paintStyle.fillStyle || currentConnectionPaintStyle.strokeStyle,
lineWidth = paintStyle.lineWidth || currentConnectionPaintStyle.lineWidth;
self.paint(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions);
return [ minx, maxx, miny, maxy];
};
};
/**
* Class: Overlays.PlainArrow
*
* A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some
* point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
* a 'call' to Arrow with foldback set appropriately.
*/
/**
* Function: Constructor
* See <Overlays.Arrow> for allowed parameters for this overlay.
*/
jsPlumb.Overlays.PlainArrow = function(params) {
params = params || {};
var p = jsPlumb.extend(params, {foldback:1});
jsPlumb.Overlays.Arrow.call(this, p);
this.type = "PlainArrow";
};
/**
* Class: Overlays.Diamond
*
* A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
* happens that in this case, that point is greater than the length of the the arrow.
*
* this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
* center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
* stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
* would be -l/4 in this case - move along one quarter of the total length.
*/
/**
* Function: Constructor
* See <Overlays.Arrow> for allowed parameters for this overlay.
*/
jsPlumb.Overlays.Diamond = function(params) {
params = params || {};
var l = params.length || 40;
var p = jsPlumb.extend(params, {length:l/2, foldback:2});
jsPlumb.Overlays.Arrow.call(this, p);
this.type = "Diamond";
};
/**
* Class: Overlays.Label
* A Label overlay. For all different renderer types (SVG/Canvas/VML), jsPlumb draws a Label overlay as a styled DIV. Version 1.3.0 of jsPlumb
* introduced the ability to set css classes on the label; this is now the preferred way for you to style a label. The 'labelStyle' parameter
* is still supported in 1.3.0 but its usage is deprecated. Under the hood, jsPlumb just turns that object into a bunch of CSS directive that it
* puts on the Label's 'style' attribute, so the end result is the same.
*/
/**
* Function: Constructor
*
* Parameters:
* cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
* defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
* label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your
* label function returns null. empty strings _will_ be painted.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
* labelStyle - (deprecated) js object containing style instructions for the label. defaults to jsPlumb.Defaults.LabelStyle.
* borderWidth - (deprecated) width of a border to paint. defaults to zero.
* borderStyle - (deprecated) strokeStyle to use when painting the border, if necessary.
*
*/
jsPlumb.Overlays.Label = function(params) {
this.type = "Label";
jsPlumb.DOMElementComponent.apply(this, arguments);
this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle;
this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
this.label = params.label || "banana";
this.connection = params.connection;
this.id = params.id;
var self = this;
var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
this.location = params.location || 0.5;
this.cachedDimensions = null; // setting on 'this' rather than using closures uses a lot less memory. just don't monkey with it!
var initialised = false,
labelText = null,
div = document.createElement("div");
div.style["position"] = "absolute";
div.style["font"] = self.labelStyle.font;
div.style["color"] = self.labelStyle.color || "black";
if (self.labelStyle.fillStyle) div.style["background"] = self.labelStyle.fillStyle;//_convertStyle(self.labelStyle.fillStyle, true);
if (self.labelStyle.borderWidth > 0) {
var dStyle = self.labelStyle.borderStyle ? self.labelStyle.borderStyle/*_convertStyle(self.labelStyle.borderStyle, true)*/ : "black";
div.style["border"] = self.labelStyle.borderWidth + "px solid " + dStyle;
}
if (self.labelStyle.padding) div.style["padding"] = self.labelStyle.padding;
var clazz = params["_jsPlumb"].overlayClass + " " +
(self.labelStyle.cssClass ? self.labelStyle.cssClass :
params.cssClass ? params.cssClass : "");
div.className = clazz;
jsPlumb.appendElement(div, params.connection.parent);
jsPlumb.getId(div);
self.attachListeners(div, self);
this.paint = function(connector, d, connectorDimensions) {
if (!initialised) {
connector.appendDisplayElement(div);
self.attachListeners(div, connector);
initialised = true;
}
div.style.left = (connectorDimensions[0] + d.minx) + "px";
div.style.top = (connectorDimensions[1] + d.miny) + "px";
};
this.getTextDimensions = function(connector) {
labelText = typeof self.label == 'function' ? self.label(self) : self.label;
div.innerHTML = labelText.replace(/\r\n/g, "<br/>");
var de = jsPlumb.CurrentLibrary.getElementObject(div),
s = jsPlumb.CurrentLibrary.getSize(de);
return {width:s[0], height:s[1]};
};
this.computeMaxSize = function(connector) {
var td = self.getTextDimensions(connector);
return td.width ? Math.max(td.width, td.height) * 1.5 : 0;
};
this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
var td = self.getTextDimensions(connector);
if (td.width != null) {
var cxy = connector.pointOnPath(self.location);
var minx = cxy.x - (td.width / 2);
var miny = cxy.y - (td.height / 2);
self.paint(connector, {
minx:minx,
miny:miny,
td:td,
cxy:cxy
}, connectorDimensions);
return [minx, minx+td.width, miny, miny+td.height];
}
else return [0,0,0,0];
};
};
// ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
// ********************************* OVERLAY CANVAS RENDERERS***********************************************************************
// ********************************* END OF OVERLAY CANVAS RENDERERS ***********************************************************************
})();/*
* jsPlumb
*
* Title:jsPlumb 1.3.2
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the VML renderers.
*
* Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://code.google.com/p/jsplumb
*
* Triple licensed under the MIT, GPL2 and Beer licenses.
*/
;(function() {
// http://ajaxian.com/archives/the-vml-changes-in-ie-8
// http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/
// http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
var vmlAttributeMap = {
"stroke-linejoin":"joinstyle",
"joinstyle":"joinstyle",
"endcap":"endcap",
"miterlimit":"miterlimit"
};
if (document.createStyleSheet) {
// this is the style rule for IE7/6: it uses a CSS class, tidy.
document.createStyleSheet().addRule(".jsplumb_vml", "behavior:url(#default#VML);position:absolute;");
// these are for VML in IE8. you have to explicitly call out which elements
// you're going to expect to support VML!
//
// try to avoid IE8. it is recommended you set X-UA-Compatible="IE=7" if you can.
//
document.createStyleSheet().addRule("jsplumb\\:textbox", "behavior:url(#default#VML);position:absolute;");
document.createStyleSheet().addRule("jsplumb\\:oval", "behavior:url(#default#VML);position:absolute;");
document.createStyleSheet().addRule("jsplumb\\:rect", "behavior:url(#default#VML);position:absolute;");
document.createStyleSheet().addRule("jsplumb\\:stroke", "behavior:url(#default#VML);position:absolute;");
document.createStyleSheet().addRule("jsplumb\\:shape", "behavior:url(#default#VML);position:absolute;");
// in this page it is also mentioned that IE requires the extra arg to the namespace
// http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
// but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either.
// var iev = document.documentMode;
//if (!iev || iev < 8)
document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml");
//else
// document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML");
}
var scale = 1000,
_atts = function(o, atts) {
for (var i in atts) {
// IE8 fix: setattribute does not work after an element has been added to the dom!
// http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
//o.setAttribute(i, atts[i]);
o[i] = atts[i];
}
},
_node = function(name, d, atts) {
atts = atts || {};
var o = document.createElement("jsplumb:" + name);
o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml";
_pos(o, d);
_atts(o, atts);
return o;
},
_pos = function(o,d) {
o.style.left = d[0] + "px";
o.style.top = d[1] + "px";
o.style.width= d[2] + "px";
o.style.height= d[3] + "px";
o.style.position = "absolute";
},
_conv = function(v) {
return Math.floor(v * scale);
},
_convertStyle = function(s, ignoreAlpha) {
var o = s,
pad = function(n) { return n.length == 1 ? "0" + n : n; },
hex = function(k) { return pad(Number(k).toString(16)); },
pattern = /(rgb[a]?\()(.*)(\))/;
if (s.match(pattern)) {
var parts = s.match(pattern)[2].split(",");
o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
if (!ignoreAlpha && parts.length == 4)
o = o + hex(parts[3]);
}
return o;
},
_applyStyles = function(node, style, component) {
var styleToWrite = {};
if (style.strokeStyle) {
styleToWrite["stroked"] = "true";
styleToWrite["strokecolor"] =_convertStyle(style.strokeStyle, true);
styleToWrite["strokeweight"] = style.lineWidth + "px";
}
else styleToWrite["stroked"] = "false";
if (style.fillStyle) {
styleToWrite["filled"] = "true";
styleToWrite["fillcolor"] = _convertStyle(style.fillStyle, true);
}
else styleToWrite["filled"] = "false";
if(style["dashstyle"]) {
if (component.strokeNode == null) {
component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] });
node.appendChild(component.strokeNode);
}
else
component.strokeNode.dashstyle = style["dashstyle"];
}
else if (style["stroke-dasharray"] && style["lineWidth"]) {
var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",",
parts = style["stroke-dasharray"].split(sep),
styleToUse = "";
for(var i = 0; i < parts.length; i++) {
styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep);
}
if (component.strokeNode == null) {
component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse });
node.appendChild(component.strokeNode);
}
else
component.strokeNode.dashstyle = styleToUse;
}
_atts(node, styleToWrite);
},
/*
* Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent.
*/
VmlComponent = function() {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
},
/*
* Base class for Vml connectors. extends VmlComponent.
*/
VmlConnector = function(params) {
var self = this;
self.strokeNode = null;
self.canvas = null;
VmlComponent.apply(this, arguments);
clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : "");
this.paint = function(d, style, anchor) {
if (style != null) {
var path = self.getPath(d), p = { "path":path };
if (style.outlineColor) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
outlineStyle = {
strokeStyle:_convertStyle(style.outlineColor),
lineWidth:outlineStrokeWidth
};
if (self.bgCanvas == null) {
p["class"] = clazz;
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
self.bgCanvas = _node("shape", d, p);
jsPlumb.appendElement(self.bgCanvas, params.parent);
_pos(self.bgCanvas, d);
displayElements.push(self.bgCanvas);
}
else {
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
_pos(self.bgCanvas, d);
_atts(self.bgCanvas, p);
}
_applyStyles(self.bgCanvas, outlineStyle, self);
}
if (self.canvas == null) {
p["class"] = clazz;
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
self.canvas = _node("shape", d, p);
jsPlumb.appendElement(self.canvas, params.parent);
displayElements.push(self.canvas);
self.attachListeners(self.canvas, self);
}
else {
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
_pos(self.canvas, d);
_atts(self.canvas, p);
}
_applyStyles(self.canvas, style, self);
}
};
var displayElements = [ self.canvas ];
this.getDisplayElements = function() {
return displayElements;
};
this.appendDisplayElement = function(el) {
self.canvas.parentNode.appendChild(el);
displayElements.push(el);
};
},
/*
*
* Base class for Vml Endpoints. extends VmlComponent.
*
*/
VmlEndpoint = function(params) {
VmlComponent.apply(this, arguments);
var vml = null, self = this;
self.canvas = document.createElement("div");
self.canvas.style["position"] = "absolute";
jsPlumb.appendElement(self.canvas, params.parent);
this.paint = function(d, style, anchor) {
var p = { };
jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
if (vml == null) {
p["class"] = jsPlumb.endpointClass;
vml = self.getVml([0,0, d[2], d[3]], p, anchor);
self.canvas.appendChild(vml);
self.attachListeners(vml, self);
}
else {
//p["coordsize"] = "1,1";//(d[2] * scale) + "," + (d[3] * scale); again, unsure.
_pos(vml, [0,0, d[2], d[3]]);
_atts(vml, p);
}
_applyStyles(vml, style);
};
};
jsPlumb.Connectors.vml.Bezier = function() {
jsPlumb.Connectors.Bezier.apply(this, arguments);
VmlConnector.apply(this, arguments);
this.getPath = function(d) {
return "m" + _conv(d[4]) + "," + _conv(d[5]) +
" c" + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[10]) + "," + _conv(d[11]) + "," + _conv(d[6]) + "," + _conv(d[7]) + " e";
};
};
jsPlumb.Connectors.vml.Straight = function() {
jsPlumb.Connectors.Straight.apply(this, arguments);
VmlConnector.apply(this, arguments);
this.getPath = function(d) {
return "m" + _conv(d[4]) + "," + _conv(d[5]) + " l" + _conv(d[6]) + "," + _conv(d[7]) + " e";
};
};
jsPlumb.Connectors.vml.Flowchart = function() {
jsPlumb.Connectors.Flowchart.apply(this, arguments);
VmlConnector.apply(this, arguments);
this.getPath = function(dimensions) {
var p = "m " + _conv(dimensions[4]) + "," + _conv(dimensions[5]) + " l";
// loop through extra points
for (var i = 0; i < dimensions[8]; i++) {
p = p + " " + _conv(dimensions[9 + (i*2)]) + "," + _conv(dimensions[10 + (i*2)]);
}
// finally draw a line to the end
p = p + " " + _conv(dimensions[6]) + "," + _conv(dimensions[7]) + " e";
return p;
};
};
jsPlumb.Endpoints.vml.Dot = function() {
jsPlumb.Endpoints.Dot.apply(this, arguments);
VmlEndpoint.apply(this, arguments);
this.getVml = function(d, atts, anchor) { return _node("oval", d, atts); };
};
jsPlumb.Endpoints.vml.Rectangle = function() {
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
VmlEndpoint.apply(this, arguments);
this.getVml = function(d, atts, anchor) { return _node("rect", d, atts); };
};
/*
* VML Image Endpoint is the same as the default image endpoint.
*/
jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image;
/**
* placeholder for Blank endpoint in vml renderer.
*/
jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank;
/**
* VML Label renderer. uses the default label renderer (which adds an element to the DOM)
*/
jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label;
var AbstractVmlArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
VmlComponent.apply(this, arguments);
var self = this, canvas = null, path =null;
var getPath = function(d, connectorDimensions) {
return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) +
" l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) +
" " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) +
" " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) +
" x e";
};
this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions) {
var p = {};
if (strokeStyle) {
p["stroked"] = "true";
p["strokecolor"] =_convertStyle(strokeStyle, true);
}
if (lineWidth) p["strokeweight"] = lineWidth + "px";
if (fillStyle) {
p["filled"] = "true";
p["fillcolor"] = fillStyle;
}
var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
w = Math.abs(xmax - xmin),
h = Math.abs(ymax - ymin),
dim = [xmin, ymin, w, h];
// for VML, we create overlays using shapes that have the same dimensions and
// coordsize as their connector - overlays calculate themselves relative to the
// connector (it's how it's been done since the original canvas implementation, because
// for canvas that makes sense).
p["path"] = getPath(d, connectorDimensions);
p["coordsize"] = (connectorDimensions[2] * scale) + "," + (connectorDimensions[3] * scale);
dim[0] = connectorDimensions[0];
dim[1] = connectorDimensions[1];
dim[2] = connectorDimensions[2];
dim[3] = connectorDimensions[3];
if (canvas == null) {
//p["class"] = jsPlumb.overlayClass; // TODO currentInstance?
canvas = _node("shape", dim, p);
connector.appendDisplayElement(canvas);
self.attachListeners(canvas, connector);
}
else {
_pos(canvas, dim);
_atts(canvas, p);
}
};
};
jsPlumb.Overlays.vml.Arrow = function() {
AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.vml.PlainArrow = function() {
AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.vml.Diamond = function() {
AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
})();/*
* jsPlumb
*
* Title:jsPlumb 1.3.2
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the SVG renderers.
*
* Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://code.google.com/p/jsplumb
*
* Triple licensed under the MIT, GPL2 and Beer licenses.
*/
/**
* SVG support for jsPlumb.
*
* things to investigate:
*
* gradients: https://developer.mozilla.org/en/svg_in_html_introduction
* css:http://tutorials.jenkov.com/svg/svg-and-css.html
* text on a path: http://www.w3.org/TR/SVG/text.html#TextOnAPath
* pointer events: https://developer.mozilla.org/en/css/pointer-events
*
*/
;(function() {
var svgAttributeMap = {
"stroke-linejoin":"stroke-linejoin",
"joinstyle":"stroke-linejoin",
"stroke-dashoffset":"stroke-dashoffset"
};
var ns = {
svg:"http://www.w3.org/2000/svg",
xhtml:"http://www.w3.org/1999/xhtml"
},
_attr = function(node, attributes) {
for (var i in attributes)
node.setAttribute(i, "" + attributes[i]);
},
_node = function(name, attributes) {
var n = document.createElementNS(ns.svg, name);
attributes = attributes || {};
attributes["version"] = "1.1";
attributes["xmnls"] = ns.xhtml;
_attr(n, attributes);
return n;
},
_pos = function(d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; },
_convertStyle = function(s, ignoreAlpha) {
var o = s,
pad = function(n) { return n.length == 1 ? "0" + n : n; },
hex = function(k) { return pad(Number(k).toString(16)); },
pattern = /(rgb[a]?\()(.*)(\))/;
if (s.match(pattern)) {
var parts = s.match(pattern)[2].split(",");
o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
if (!ignoreAlpha && parts.length == 4)
o = o + hex(parts[3]);
}
return o;
},
_clearGradient = function(parent) {
for (var i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes[i].tagName == "linearGradient" || parent.childNodes[i].tagName == "radialGradient")
parent.removeChild(parent.childNodes[i]);
}
},
_updateGradient = function(parent, node, style, dimensions) {
var id = "jsplumb_gradient_" + (new Date()).getTime();
// first clear out any existing gradient
_clearGradient(parent);
// this checks for an 'offset' property in the gradient, and in the absence of it, assumes
// we want a linear gradient. if it's there, we create a radial gradient.
// it is possible that a more explicit means of defining the gradient type would be
// better. relying on 'offset' means that we can never have a radial gradient that uses
// some default offset, for instance.
if (!style.gradient.offset) {
var g = _node("linearGradient", {id:id});
parent.appendChild(g);
}
else {
var g = _node("radialGradient", {
id:id
});
parent.appendChild(g);
}
// the svg radial gradient seems to treat stops in the reverse
// order to how canvas does it. so we want to keep all the maths the same, but
// iterate the actual style declarations in reverse order, if the x indexes are not in order.
for (var i = 0; i < style.gradient.stops.length; i++) {
// Straight Connectors and Bezier connectors act slightly differently; this code is a bit of a kludge. but next version of
// jsplumb will be replacing both Straight and Bezier to be generic instances of 'Connector', which has a list of segments.
// so, not too concerned about leaving this in for now.
var styleToUse = i;
if (dimensions.length == 8)
styleToUse = dimensions[4] < dimensions[6] ? i: style.gradient.stops.length - 1 - i;
else
styleToUse = dimensions[4] < dimensions[6] ? style.gradient.stops.length - 1 - i : i;
var stopColor = _convertStyle(style.gradient.stops[styleToUse][1], true);
var s = _node("stop", {"offset":Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color":stopColor});
g.appendChild(s);
}
var applyGradientTo = style.strokeStyle ? "stroke" : "fill";
node.setAttribute("style", applyGradientTo + ":url(#" + id + ")");
},
_applyStyles = function(parent, node, style, dimensions) {
if (style.gradient) {
_updateGradient(parent, node, style, dimensions);
}
else {
// make sure we clear any existing gradient
_clearGradient(parent);
node.setAttribute("style", "");
}
node.setAttribute("fill", style.fillStyle ? _convertStyle(style.fillStyle, true) : "none");
node.setAttribute("stroke", style.strokeStyle ? _convertStyle(style.strokeStyle, true) : "none");
if (style.lineWidth) {
node.setAttribute("stroke-width", style.lineWidth);
}
// in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
// the syntax in VML but is actually kind of nasty: values are given in the pixel
// coordinate space, whereas in VML they are multiples of the width of the stroked
// line, which makes a lot more sense. for that reason, jsPlumb is supporting both
// the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
// VML, which will be the preferred method. the code below this converts a dashstyle
// attribute given in terms of stroke width into a pixel representation, by using the
// stroke's lineWidth.
if(style["stroke-dasharray"]) {
node.setAttribute("stroke-dasharray", style["stroke-dasharray"]);
}
if (style["dashstyle"] && style["lineWidth"]) {
var sep = style["dashstyle"].indexOf(",") == -1 ? " " : ",",
parts = style["dashstyle"].split(sep),
styleToUse = "";
parts.forEach(function(p) {
styleToUse += (Math.floor(p * style.lineWidth) + sep);
});
node.setAttribute("stroke-dasharray", styleToUse);
}
// extra attributes such as join type, dash offset.
for (var i in svgAttributeMap) {
if (style[i]) {
node.setAttribute(svgAttributeMap[i], style[i]);
}
}
},
_decodeFont = function(f) {
var r = /([0-9].)(p[xt])\s(.*)/;
var bits = f.match(r);
return {size:bits[1] + bits[2], font:bits[3]};
};
/*
* Base class for SVG components.
*/
var SvgComponent = function(cssClass, originalArgs, pointerEventsSpec) {
var self = this;
pointerEventsSpec = pointerEventsSpec || "all";
jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
self.canvas = null, self.path = null, self.svg = null;
this.setHover = function() { };
self.canvas = document.createElement("div");
self.canvas.style["position"] = "absolute";
jsPlumb.sizeCanvas(self.canvas,0,0,1,1);
var clazz = cssClass + " " + (originalArgs[0].cssClass || "");
self.canvas.className = clazz;
self.svg = _node("svg", {
"style":"",
"width":0,
"height":0,
"pointer-events":pointerEventsSpec/*,
"class": clazz*/
});
jsPlumb.appendElement(self.canvas, originalArgs[0]["parent"]);
self.canvas.appendChild(self.svg);
// TODO this displayElement stuff is common between all components, across all
// renderers. would be best moved to jsPlumbUIComponent.
var displayElements = [ self.canvas ];
this.getDisplayElements = function() {
return displayElements;
};
this.appendDisplayElement = function(el) {
displayElements.push(el);
};
this.paint = function(d, style, anchor) {
if (style != null) {
jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
_attr(self.svg, {
"style":_pos([0,0,d[2], d[3]]),
"width": d[2],
"height": d[3]
});
self._paint.apply(this, arguments);
}
};
};
/*
* Base class for SVG connectors.
*/
var SvgConnector = function(params) {
var self = this;
SvgComponent.apply(this, [ params["_jsPlumb"].connectorClass, arguments, "none" ]);
this._paint = function(d, style) {
var p = self.getPath(d), a = { "d":p }, outlineStyle = null;
a["pointer-events"] = "all";
// outline style. actually means drawing an svg object underneath the main one.
if (style.outlineColor) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
outlineStyle = {
strokeStyle:_convertStyle(style.outlineColor),
lineWidth:outlineStrokeWidth
};
if (self.bgPath == null) {
self.bgPath = _node("path", a);
self.svg.appendChild(self.bgPath);
self.attachListeners(self.bgPath, self);
}
else {
_attr(self.bgPath, a);
}
_applyStyles(self.svg, self.bgPath, outlineStyle, d);
}
if (self.path == null) {
self.path = _node("path", a);
self.svg.appendChild(self.path);
self.attachListeners(self.path, self);
}
else {
_attr(self.path, a);
}
_applyStyles(self.svg, self.path, style, d);
};
};
/*
* SVG Bezier Connector
*/
jsPlumb.Connectors.svg.Bezier = function(params) {
jsPlumb.Connectors.Bezier.apply(this, arguments);
SvgConnector.apply(this, arguments);
this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " C " + d[8] + " " + d[9] + " " + d[10] + " " + d[11] + " " + d[6] + " " + d[7]; };
};
/*
* SVG straight line Connector
*/
jsPlumb.Connectors.svg.Straight = function(params) {
jsPlumb.Connectors.Straight.apply(this, arguments);
SvgConnector.apply(this, arguments);
this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " L " + d[6] + " " + d[7]; };
};
jsPlumb.Connectors.svg.Flowchart = function() {
var self = this;
jsPlumb.Connectors.Flowchart.apply(this, arguments);
SvgConnector.apply(this, arguments);
this.getPath = function(dimensions) {
var p = "M " + dimensions[4] + "," + dimensions[5];
// loop through extra points
for (var i = 0; i < dimensions[8]; i++) {
p = p + " L " + dimensions[9 + (i*2)] + " " + dimensions[10 + (i*2)];
}
// finally draw a line to the end
p = p + " " + dimensions[6] + "," + dimensions[7];
return p;
};
};
/*
* Base class for SVG endpoints.
*/
var SvgEndpoint = function(params) {
var self = this;
SvgComponent.apply(this, [ params["_jsPlumb"].endpointClass, arguments, "all" ]);
this._paint = function(d, style) {
var s = jsPlumb.extend({}, style);
if (s.outlineColor) {
s.strokeWidth = s.outlineWidth;
s.strokeStyle = _convertStyle(s.outlineColor, true);
}
if (self.node == null) {
self.node = self.makeNode(d, s);
self.svg.appendChild(self.node);
self.attachListeners(self.node, self);
}
_applyStyles(self.svg, self.node, s, d);
_pos(self.node, d);
};
};
/*
* SVG Dot Endpoint
*/
jsPlumb.Endpoints.svg.Dot = function() {
jsPlumb.Endpoints.Dot.apply(this, arguments);
SvgEndpoint.apply(this, arguments);
this.makeNode = function(d, style) {
return _node("circle", {
"cx" : d[2] / 2,
"cy" : d[3] / 2,
"r" : d[2] / 2
});
};
};
/*
* SVG Rectangle Endpoint
*/
jsPlumb.Endpoints.svg.Rectangle = function() {
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
SvgEndpoint.apply(this, arguments);
this.makeNode = function(d, style) {
return _node("rect", {
"width":d[2],
"height":d[3]
});
};
};
/*
* SVG Image Endpoint is the default image endpoint.
*/
jsPlumb.Endpoints.svg.Image = jsPlumb.Endpoints.Image;
/*
* Blank endpoint in svg renderer is the default Blank endpoint.
*/
jsPlumb.Endpoints.svg.Blank = jsPlumb.Endpoints.Blank;
/*
* Label endpoint in svg renderer is the default Label endpoint.
*/
jsPlumb.Overlays.svg.Label = jsPlumb.Overlays.Label;
var AbstractSvgArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
var self = this, path =null;
this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
if (path == null) {
path = _node("path");
connector.svg.appendChild(path);
self.attachListeners(path, connector);
self.attachListeners(path, self);
}
_attr(path, {
"d" : makePath(d),
stroke : strokeStyle ? strokeStyle : null,
fill : fillStyle ? fillStyle : null
});
};
var makePath = function(d) {
return "M" + d.hxy.x + "," + d.hxy.y +
" L" + d.tail[0].x + "," + d.tail[0].y +
" L" + d.cxy.x + "," + d.cxy.y +
" L" + d.tail[1].x + "," + d.tail[1].y +
" L" + d.hxy.x + "," + d.hxy.y;
};
};
jsPlumb.Overlays.svg.Arrow = function() {
AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.svg.PlainArrow = function() {
AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.svg.Diamond = function() {
AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
})();/*
* jsPlumb
*
* Title:jsPlumb 1.3.2
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the HTML5 canvas renderers.
*
* Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://code.google.com/p/jsplumb
*
* Triple licensed under the MIT, GPL2 and Beer licenses.
*/
;(function() {
// ********************************* CANVAS RENDERERS FOR CONNECTORS AND ENDPOINTS *******************************************************************
// TODO refactor to renderer common script. put a ref to jsPlumb.sizeCanvas in there too.
var _connectionBeingDragged = null,
_getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); },
_setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); },
_addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); },
_hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
_removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); },
_getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
_getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
_getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); },
_pageXY = function(el) { return jsPlumb.CurrentLibrary.getPageXY(el); },
_clientXY = function(el) { return jsPlumb.CurrentLibrary.getClientXY(el); },
_setOffset = function(el, o) { jsPlumb.CurrentLibrary.setOffset(el, o); };
/*
* Class:CanvasMouseAdapter
* Provides support for mouse events on canvases.
*/
var CanvasMouseAdapter = function() {
var self = this;
self.overlayPlacements = [];
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
jsPlumb.EventGenerator.apply(this, arguments);
/**
* returns whether or not the given event is ojver a painted area of the canvas.
*/
this._over = function(e) {
var o = _getOffset(_getElementObject(self.canvas)),
pageXY = _pageXY(e),
x = pageXY[0] - o.left, y = pageXY[1] - o.top;
if (x > 0 && y > 0 && x < self.canvas.width && y < self.canvas.height) {
// first check overlays
for ( var i = 0; i < self.overlayPlacements.length; i++) {
var p = self.overlayPlacements[i];
if (p && (p[0] <= x && p[1] >= x && p[2] <= y && p[3] >= y))
return true;
}
// then the canvas
var d = self.canvas.getContext("2d").getImageData(parseInt(x), parseInt(y), 1, 1);
return d.data[0] != 0 || d.data[1] != 0 || d.data[2] != 0 || d.data[3] != 0;
}
return false;
};
var _mouseover = false;
var _mouseDown = false, _posWhenMouseDown = null, _mouseWasDown = false;
var _nullSafeHasClass = function(el, clazz) {
return el != null && _hasClass(el, clazz);
};
this.mousemove = function(e) {
var pageXY = _pageXY(e), clientXY = _clientXY(e),
ee = document.elementFromPoint(clientXY[0], clientXY[1]),
eventSourceWasOverlay = _nullSafeHasClass(ee, "_jsPlumb_overlay");
var _continue = _connectionBeingDragged == null && (_nullSafeHasClass(ee, "_jsPlumb_endpoint") || _nullSafeHasClass(ee, "_jsPlumb_connector"));
if (!_mouseover && _continue && self._over(e)) {
_mouseover = true;
self.fire("mouseenter", self, e);
return true;
}
// TODO here there is a remote chance that the overlay the mouse moved onto
// is actually not an overlay for the current component. a more thorough check would
// be to ensure the overlay belonged to the current component.
else if (_mouseover && (!self._over(e) || !_continue) && !eventSourceWasOverlay) {
_mouseover = false;
self.fire("mouseexit", self, e);
}
self.fire("mousemove", self, e);
};
this.click = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("click", self, e);
_mouseWasDown = false;
};
this.dblclick = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("dblclick", self, e);
_mouseWasDown = false;
};
this.mousedown = function(e) {
if(self._over(e) && !_mouseDown) {
_mouseDown = true;
_posWhenMouseDown = _getOffset(_getElementObject(self.canvas));
self.fire("mousedown", self, e);
}
};
this.mouseup = function(e) {
//if (self == _connectionBeingDragged) _connectionBeingDragged = null;
_mouseDown = false;
self.fire("mouseup", self, e);
};
};
var _newCanvas = function(params) {
var canvas = document.createElement("canvas");
jsPlumb.appendElement(canvas, params.parent);
canvas.style.position = "absolute";
if (params["class"]) canvas.className = params["class"];
// set an id. if no id on the element and if uuid was supplied it
// will be used, otherwise we'll create one.
params["_jsPlumb"].getId(canvas, params.uuid);
return canvas;
};
/**
* Class:CanvasConnector
* Superclass for Canvas Connector renderers.
*/
var CanvasConnector = jsPlumb.CanvasConnector = function(params) {
CanvasMouseAdapter.apply(this, arguments);
var _paintOneStyle = function(dim, aStyle) {
self.ctx.save();
jsPlumb.extend(self.ctx, aStyle);
if (aStyle.gradient) {
var g = self.createGradient(dim, self.ctx);
for ( var i = 0; i < aStyle.gradient.stops.length; i++)
g.addColorStop(aStyle.gradient.stops[i][0], aStyle.gradient.stops[i][1]);
self.ctx.strokeStyle = g;
}
self._paint(dim);
self.ctx.restore();
};
var self = this,
clazz = self._jsPlumb.connectorClass + " " + (params.cssClass || "");
self.canvas = _newCanvas({
"class":clazz,
_jsPlumb:self._jsPlumb,
parent:params.parent
});
self.ctx = self.canvas.getContext("2d");
var displayElements = [ self.canvas ];
this.getDisplayElements = function() {
return displayElements;
};
this.appendDisplayElement = function(el) {
displayElements.push(el);
};
self.paint = function(dim, style) {
if (style != null) {
jsPlumb.sizeCanvas(self.canvas, dim[0], dim[1], dim[2], dim[3]);
if (style.outlineColor != null) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
var outlineStyle = {
strokeStyle:style.outlineColor,
lineWidth:outlineStrokeWidth
};
_paintOneStyle(dim, outlineStyle);
}
_paintOneStyle(dim, style);
}
};
};
/**
* Class:CanvasEndpoint
* Superclass for Canvas Endpoint renderers.
*/
var CanvasEndpoint = function(params) {
var self = this;
CanvasMouseAdapter.apply(this, arguments);
var clazz = self._jsPlumb.endpointClass + " " + (params.cssClass || "");
self.canvas = _newCanvas({
"class":clazz,
_jsPlumb:self._jsPlumb,
parent:params.parent
});
self.ctx = self.canvas.getContext("2d");
this.paint = function(d, style, anchor) {
jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
if (style.outlineColor != null) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
var outlineStyle = {
strokeStyle:style.outlineColor,
lineWidth:outlineStrokeWidth
};
// _paintOneStyle(d, outlineStyle);
}
self._paint.apply(this, arguments);
};
};
jsPlumb.Endpoints.canvas.Dot = function(params) {
var self = this;
jsPlumb.Endpoints.Dot.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
var parseValue = function(value) {
try {
return parseInt(value);
}
catch(e) {
if (value.substring(value.length - 1) == '%')
return parseInt(value.substring(0, value - 1));
}
};
var calculateAdjustments = function(gradient) {
var offsetAdjustment = self.defaultOffset, innerRadius = self.defaultInnerRadius;
gradient.offset && (offsetAdjustment = parseValue(gradient.offset));
gradient.innerRadius && (innerRadius = parseValue(gradient.innerRadius));
return [offsetAdjustment, innerRadius];
};
this._paint = function(d, style, anchor) {
if (style != null) {
var ctx = self.canvas.getContext('2d'), orientation = anchor.getOrientation();
jsPlumb.extend(ctx, style);
if (style.gradient) {
var adjustments = calculateAdjustments(style.gradient),
yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0],
xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0],
g = ctx.createRadialGradient(d[4], d[4], d[4], d[4] + xAdjust, d[4] + yAdjust, adjustments[1]);
for (var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.fillStyle = g;
}
ctx.beginPath();
ctx.arc(d[4], d[4], d[4], 0, Math.PI*2, true);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
}
};
};
jsPlumb.Endpoints.canvas.Rectangle = function(params) {
var self = this;
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
this._paint = function(d, style, anchor) {
var ctx = self.canvas.getContext("2d"), orientation = anchor.getOrientation();
jsPlumb.extend(ctx, style);
/* canvas gradient */
if (style.gradient) {
// first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
var y1 = orientation[1] == 1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
var y2 = orientation[1] == -1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
var x1 = orientation[0] == 1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
var x2 = orientation[0] == -1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
var g = ctx.createLinearGradient(x1,y1,x2,y2);
for (var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.fillStyle = g;
}
ctx.beginPath();
ctx.rect(0, 0, d[2], d[3]);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
};
};
jsPlumb.Endpoints.canvas.Triangle = function(params) {
var self = this;
jsPlumb.Endpoints.Triangle.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
this._paint = function(d, style, anchor)
{
var width = d[2], height = d[3], x = d[0], y = d[1];
var ctx = self.canvas.getContext('2d');
var offsetX = 0, offsetY = 0, angle = 0;
if( orientation[0] == 1 )
{
offsetX = width;
offsetY = height;
angle = 180;
}
if( orientation[1] == -1 )
{
offsetX = width;
angle = 90;
}
if( orientation[1] == 1 )
{
offsetY = height;
angle = -90;
}
ctx.fillStyle = style.fillStyle;
ctx.translate(offsetX, offsetY);
ctx.rotate(angle * Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(width/2, height/2);
ctx.lineTo(0, height);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
};
};
/*
* Canvas Image Endpoint: uses the default version, which creates an <img> tag.
*/
jsPlumb.Endpoints.canvas.Image = jsPlumb.Endpoints.Image;
/*
* Blank endpoint in all renderers is just the default Blank endpoint.
*/
jsPlumb.Endpoints.canvas.Blank = jsPlumb.Endpoints.Blank;
/*
* Canvas Bezier Connector. Draws a Bezier curve onto a Canvas element.
*/
jsPlumb.Connectors.canvas.Bezier = function() {
var self = this;
jsPlumb.Connectors.Bezier.apply(this, arguments);
CanvasConnector.apply(this, arguments);
this._paint = function(dimensions) {
self.ctx.beginPath();
self.ctx.moveTo(dimensions[4], dimensions[5]);
self.ctx.bezierCurveTo(dimensions[8], dimensions[9], dimensions[10], dimensions[11], dimensions[6], dimensions[7]);
self.ctx.stroke();
};
// TODO i doubt this handles the case that source and target are swapped.
this.createGradient = function(dim, ctx, swap) {
return /*(swap) ? self.ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : */self.ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
};
};
/*
* Canvas straight line Connector. Draws a straight line onto a Canvas element.
*/
jsPlumb.Connectors.canvas.Straight = function() {
var self = this;
jsPlumb.Connectors.Straight.apply(this, arguments);
CanvasConnector.apply(this, arguments);
this._paint = function(dimensions) {
self.ctx.beginPath();
self.ctx.moveTo(dimensions[4], dimensions[5]);
self.ctx.lineTo(dimensions[6], dimensions[7]);
self.ctx.stroke();
};
// TODO this does not handle the case that src and target are swapped.
this.createGradient = function(dim, ctx) {
return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
};
};
jsPlumb.Connectors.canvas.Flowchart = function() {
var self = this;
jsPlumb.Connectors.Flowchart.apply(this, arguments);
CanvasConnector.apply(this, arguments);
this._paint = function(dimensions) {
self.ctx.beginPath();
self.ctx.moveTo(dimensions[4], dimensions[5]);
// loop through extra points
for (var i = 0; i < dimensions[8]; i++) {
self.ctx.lineTo(dimensions[9 + (i*2)], dimensions[10 + (i*2)]);
}
// finally draw a line to the end
self.ctx.lineTo(dimensions[6], dimensions[7]);
self.ctx.stroke();
};
this.createGradient = function(dim, ctx) {
return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
};
};
// ********************************* END OF CANVAS RENDERERS *******************************************************************
jsPlumb.Overlays.canvas.Label = jsPlumb.Overlays.Label;
/**
* a placeholder right now, really just exists to mirror the fact that there are SVG and VML versions of this.
*/
var CanvasOverlay = function() {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
};
var AbstractCanvasArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
CanvasOverlay.apply(this, arguments);
this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
var ctx = connector.ctx;
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.moveTo(d.hxy.x, d.hxy.y);
ctx.lineTo(d.tail[0].x, d.tail[0].y);
ctx.lineTo(d.cxy.x, d.cxy.y);
ctx.lineTo(d.tail[1].x, d.tail[1].y);
ctx.lineTo(d.hxy.x, d.hxy.y);
ctx.closePath();
if (strokeStyle) {
ctx.strokeStyle = strokeStyle;
ctx.stroke();
}
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
};
};
jsPlumb.Overlays.canvas.Arrow = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.canvas.PlainArrow = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.canvas.Diamond = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
})();/*
* jsPlumb
*
* Title:jsPlumb 1.3.2
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the MooTools adapter.
*
* Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://code.google.com/p/jsplumb
*
* Triple licensed under the MIT, GPL2 and Beer licenses.
*/
;(function() {
/*
* overrides the FX class to inject 'step' functionality, which MooTools does not
* offer, and which makes me sad. they don't seem keen to add it, either, despite
* the fact that it could be useful:
*
* https://mootools.lighthouseapp.com/projects/2706/tickets/668
*
*/
var jsPlumbMorph = new Class({
Extends:Fx.Morph,
onStep : null,
initialize : function(el, options) {
this.parent(el, options);
if (options['onStep']) {
this.onStep = options['onStep'];
}
},
step : function(now) {
this.parent(now);
if (this.onStep) {
try { this.onStep(); }
catch(e) { }
}
}
});
var _droppables = {},
_droppableOptions = {},
_draggablesByScope = {},
_draggablesById = {},
_droppableScopesById = {};
/*
*
*/
var _executeDroppableOption = function(el, dr, event) {
if (dr) {
var id = dr.get("id");
if (id) {
var options = _droppableOptions[id];
if (options) {
if (options[event]) {
options[event](el, dr);
}
}
}
}
};
var _checkHover = function(el, entering) {
if (el) {
var id = el.get("id");
if (id) {
var options = _droppableOptions[id];
if (options) {
if (options['hoverClass']) {
if (entering) el.addClass(options['hoverClass']);
else el.removeClass(options['hoverClass']);
}
}
}
}
};
/**
* adds the given value to the given list, with the given scope. creates the scoped list
* if necessary.
* used by initDraggable and initDroppable.
*/
var _add = function(list, scope, value) {
var l = list[scope];
if (!l) {
l = [];
list[scope] = l;
}
l.push(value);
};
/*
* gets an "element object" from the given input. this means an object that is used by the
* underlying library on which jsPlumb is running. 'el' may already be one of these objects,
* in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
* function is used to find the element, using the given String as the element's id.
*/
var _getElementObject = function(el) {
return $(el);
};
jsPlumb.CurrentLibrary = {
/**
* adds the given class to the element object.
*/
addClass : function(el, clazz) {
el.addClass(clazz);
},
animate : function(el, properties, options) {
var m = new jsPlumbMorph(el, options);
m.start(properties);
},
appendElement : function(child, parent) {
_getElementObject(parent).grab(child);
},
bind : function(el, event, callback) {
el = _getElementObject(el);
el.addEvent(event, callback);
},
dragEvents : {
'start':'onStart', 'stop':'onComplete', 'drag':'onDrag', 'step':'onStep',
'over':'onEnter', 'out':'onLeave','drop':'onDrop', 'complete':'onComplete'
},
/*
* wrapper around the library's 'extend' functionality (which it hopefully has.
* otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
* instead. it's not like its hard.
*/
extend : function(o1, o2) {
return $extend(o1, o2);
},
/**
* gets the named attribute from the given element object.
*/
getAttribute : function(el, attName) {
return el.get(attName);
},
getClientXY : function(eventObject) {
return [eventObject.event.clientX, eventObject.event.clientY];
},
getDragObject : function(eventArgs) {
return eventArgs[0];
},
getDragScope : function(el) {
var id = jsPlumb.getId(el);
var drags = _draggablesById[id];
return drags[0].scope;
},
getDropScope : function(el) {
var id = jsPlumb.getId(el);
return _droppableScopesById[id];
},
getElementObject : _getElementObject,
/*
gets the offset for the element object. this should return a js object like this:
{ left:xxx, top: xxx}
*/
getOffset : function(el) {
var p = el.getPosition();
return { left:p.x, top:p.y };
},
getPageXY : function(eventObject) {
return [eventObject.event.pageX, eventObject.event.pageY];
},
getParent : function(el) {
return jsPlumb.CurrentLibrary.getElementObject(el).getParent();
},
getScrollLeft : function(el) {
return null;
},
getScrollTop : function(el) {
return null;
},
getSize : function(el) {
var s = el.getSize();
return [s.x, s.y];
},
/*
* takes the args passed to an event function and returns you an object that gives the
* position of the object being moved, as a js object with the same params as the result of
* getOffset, ie: { left: xxx, top: xxx }.
*/
getUIPosition : function(eventArgs) {
var ui = eventArgs[0],
p = jsPlumb.CurrentLibrary.getElementObject(ui).getPosition();
return { left:p.x, top:p.y };
},
hasClass : function(el, clazz) {
return el.hasClass(clazz);
},
initDraggable : function(el, options) {
var id = jsPlumb.getId(el);
var drag = _draggablesById[id];
if (!drag) {
var originalZIndex = 0, originalCursor = null;
var dragZIndex = jsPlumb.Defaults.DragOptions.zIndex || 2000;
options['onStart'] = jsPlumb.wrap(options['onStart'], function()
{
originalZIndex = this.element.getStyle('z-index');
this.element.setStyle('z-index', dragZIndex);
if (jsPlumb.Defaults.DragOptions.cursor) {
originalCursor = this.element.getStyle('cursor');
this.element.setStyle('cursor', jsPlumb.Defaults.DragOptions.cursor);
}
});
options['onComplete'] = jsPlumb.wrap(options['onComplete'], function()
{
this.element.setStyle('z-index', originalZIndex);
if (originalCursor) {
this.element.setStyle('cursor', originalCursor);
}
});
// DROPPABLES:
var scope = options['scope'] || jsPlumb.Defaults.Scope;
var filterFunc = function(entry) {
return entry.get("id") != el.get("id");
};
var droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
options['droppables'] = droppables;
options['onLeave'] = jsPlumb.wrap(options['onLeave'], function(el, dr) {
if (dr) {
_checkHover(dr, false);
_executeDroppableOption(el, dr, 'onLeave');
}
});
options['onEnter'] = jsPlumb.wrap(options['onEnter'], function(el, dr) {
if (dr) {
_checkHover(dr, true);
_executeDroppableOption(el, dr, 'onEnter');
}
});
options['onDrop'] = function(el, dr) {
if (dr) {
_checkHover(dr, false);
_executeDroppableOption(el, dr, 'onDrop');
}
};
drag = new Drag.Move(el, options);
drag.scope = scope;
//console.log("drag scope initialized to ", scope);
_add(_draggablesByScope, scope, drag);
_add(_draggablesById, el.get("id"), drag);
// test for disabled.
if (options.disabled) drag.detach();
}
return drag;
},
initDroppable : function(el, options) {
var scope = options['scope'] || jsPlumb.Defaults.Scope;
_add(_droppables, scope, el);
var id = jsPlumb.getId(el);
_droppableOptions[id] = options;
_droppableScopesById[id] = scope;
var filterFunc = function(entry) { return entry.element != el; };
var draggables = _draggablesByScope[scope] ? _draggablesByScope[scope].filter(filterFunc) : [];
for (var i = 0; i < draggables.length; i++) {
draggables[i].droppables.push(el);
}
},
isAlreadyDraggable : function(el) {
return _draggablesById[jsPlumb.getId(el)] != null;
},
isDragSupported : function(el, options) {
return typeof Drag != 'undefined' ;
},
/*
* you need Drag.Move imported to make drop work.
*/
isDropSupported : function(el, options) {
return (typeof Drag != undefined && typeof Drag.Move != undefined);
},
/**
* removes the given class from the element object.
*/
removeClass : function(el, clazz) {
el.removeClass(clazz);
},
removeElement : function(element, parent) {
_getElementObject(element).dispose(); // ??
},
/**
* sets the named attribute on the given element object.
*/
setAttribute : function(el, attName, attValue) {
el.set(attName, attValue);
},
setDraggable : function(el, draggable) {
var draggables = _draggablesById[el.get("id")];
if (draggables) {
draggables.each(function(d) {
if (draggable) d.attach(); else d.detach();
});
}
},
setDragScope : function(el, scope) {
var drag = _draggablesById[el.get("id")];
var filterFunc = function(entry) {
return entry.get("id") != el.get("id");
};
var droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
drag[0].droppables = droppables;
},
setOffset : function(el, o) {
_getElementObject(el).setPosition({x:o.left, y:o.top});
}
};
window.addEvent('domready', jsPlumb.init);
})();
(function(){if(typeof Math.sgn=="undefined")Math.sgn=function(a){return a==0?0:a>0?1:-1};var p={subtract:function(a,b){return{x:a.x-b.x,y:a.y-b.y}},dotProduct:function(a,b){return a.x*b.x+a.y*b.y},square:function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},scale:function(a,b){return{x:a.x*b,y:a.y*b}}},y=Math.pow(2,-65),u=function(a,b){for(var g=[],d=b.length-1,h=2*d-1,f=[],c=[],l=[],k=[],i=[[1,0.6,0.3,0.1],[0.4,0.6,0.6,0.4],[0.1,0.3,0.6,1]],e=0;e<=d;e++)f[e]=p.subtract(b[e],a);for(e=0;e<=d-1;e++){c[e]=
p.subtract(b[e+1],b[e]);c[e]=p.scale(c[e],3)}for(e=0;e<=d-1;e++)for(var m=0;m<=d;m++){l[e]||(l[e]=[]);l[e][m]=p.dotProduct(c[e],f[m])}for(e=0;e<=h;e++){k[e]||(k[e]=[]);k[e].y=0;k[e].x=parseFloat(e)/h}h=d-1;for(f=0;f<=d+h;f++){c=Math.min(f,d);for(e=Math.max(0,f-h);e<=c;e++){j=f-e;k[e+j].y+=l[j][e]*i[j][e]}}d=b.length-1;k=s(k,2*d-1,g,0);h=p.subtract(a,b[0]);l=p.square(h);for(e=i=0;e<k;e++){h=p.subtract(a,t(b,d,g[e],null,null));h=p.square(h);if(h<l){l=h;i=g[e]}}h=p.subtract(a,b[d]);h=p.square(h);if(h<
l){l=h;i=1}return{location:i,distance:l}},s=function(a,b,g,d){var h=[],f=[],c=[],l=[],k=0,i,e;e=Math.sgn(a[0].y);for(var m=1;m<=b;m++){i=Math.sgn(a[m].y);i!=e&&k++;e=i}switch(k){case 0:return 0;case 1:if(d>=64){g[0]=(a[0].x+a[b].x)/2;return 1}var n,o,q;k=a[0].y-a[b].y;i=a[b].x-a[0].x;e=a[0].x*a[b].y-a[b].x*a[0].y;m=max_distance_below=0;for(o=1;o<b;o++){q=k*a[o].x+i*a[o].y+e;if(q>m)m=q;else if(q<max_distance_below)max_distance_below=q}n=k;o=i;q=e-m;n=0*o-n*1;n=1/n;m=(1*q-o*0)*n;n=k;o=i;q=e-max_distance_below;
n=0*o-n*1;n=1/n;k=(1*q-o*0)*n;if(Math.max(m,k)-Math.min(m,k)<y?1:0){c=a[b].x-a[0].x;l=a[b].y-a[0].y;g[0]=0+1*(c*(a[0].y-0)-l*(a[0].x-0))*(1/(c*0-l*1));return 1}}t(a,b,0.5,h,f);a=s(h,b,c,d+1);b=s(f,b,l,d+1);for(d=0;d<a;d++)g[d]=c[d];for(d=0;d<b;d++)g[d+a]=l[d];return a+b},t=function(a,b,g,d,h){for(var f=[[]],c=0;c<=b;c++)f[0][c]=a[c];for(a=1;a<=b;a++)for(c=0;c<=b-a;c++){f[a]||(f[a]=[]);f[a][c]||(f[a][c]={});f[a][c].x=(1-g)*f[a-1][c].x+g*f[a-1][c+1].x;f[a][c].y=(1-g)*f[a-1][c].y+g*f[a-1][c+1].y}if(d!=
null)for(c=0;c<=b;c++)d[c]=f[c][0];if(h!=null)for(c=0;c<=b;c++)h[c]=f[b-c][c];return f[b][0]},v={},z=function(a){var b=v[a];if(!b){b=[];var g=function(i){return function(){return i}},d=function(){return function(i){return i}},h=function(){return function(i){return 1-i}},f=function(i){return function(e){for(var m=1,n=0;n<i.length;n++)m*=i[n](e);return m}};b.push(new function(){return function(i){return Math.pow(i,a)}});for(var c=1;c<a;c++){for(var l=[new g(a)],k=0;k<a-c;k++)l.push(new d);for(k=0;k<
c;k++)l.push(new h);b.push(new f(l))}b.push(new function(){return function(i){return Math.pow(1-i,a)}});v[a]=b}return b},r=function(a,b){for(var g=z(a.length-1),d=0,h=0,f=0;f<a.length;f++){d+=a[f].x*g[f](b);h+=a[f].y*g[f](b)}return{x:d,y:h}},w=function(a,b,g){var d=r(a,b),h=0;b=b;for(var f=g>0?1:-1,c=null;h<Math.abs(g);){b+=0.0050*f;c=r(a,b);h+=Math.sqrt(Math.pow(c.x-d.x,2)+Math.pow(c.y-d.y,2));d=c}return{point:c,location:b}},x=function(a,b){var g=r(a,b),d=r(a.slice(0,a.length-1),b);return Math.atan((d.y-
g.y)/(d.x-g.x))};window.jsBezier={distanceFromCurve:u,gradientAtPoint:x,nearestPointOnCurve:function(a,b){var g=u(a,b);return{point:t(b,b.length-1,g.location,null,null),location:g.location}},pointOnCurve:r,pointAlongCurveFrom:function(a,b,g){return w(a,b,g).point},perpendicularToCurveAt:function(a,b,g,d){d=d==null?0:d;b=w(a,b,d);a=x(a,b.location);d=Math.atan(-1/a);a=g/2*Math.sin(d);g=g/2*Math.cos(d);return[{x:b.point.x+g,y:b.point.y+a},{x:b.point.x-g,y:b.point.y-a}]}}})();
|
doubleblacktech/learn-plumb
|
archive/1.3.2/mootools.jsPlumb-1.3.2-all.js
|
JavaScript
|
mit
| 229,734 |
import Users from 'meteor/nova:users';
import Flags from "./collection.js";
/**
*
* Flag Methods
*
*/
Flags.methods = {};
/**
* @summary Insert a flag in the database (note: optional flag properties not listed here)
* @param {Object} flag - the flag being inserted
* @param {string} flag.userId - the id of the user the flag belongs to
* @param {string} flag.title - the flag's title
*/
Flags.methods.new = function (flag) {
const currentUser = Meteor.users.findOne(flag.userId);
flag = Telescope.callbacks.run("flags.new.sync", flag, currentUser);
flag._id = Flags.insert(flag);
// note: query for flag to get fresh document with collection-hooks effects applied
Telescope.callbacks.runAsync("flags.new.async", Flags.findOne(flag._id));
return flag;
};
/**
* @summary Edit a flag in the database
* @param {string} flagId – the ID of the flag being edited
* @param {Object} modifier – the modifier object
* @param {Object} flag - the current flag object
*/
Flags.methods.edit = function (flagId, modifier, flag) {
if (typeof flag === "undefined") {
flag = Flags.findOne(flagId);
}
modifier = Telescope.callbacks.run("flags.edit.sync", modifier, flag);
Flags.update(flagId, modifier);
Telescope.callbacks.runAsync("flags.edit.async", Flags.findOne(flagId), flag);
return Flags.findOne(flagId);
};
var flagViews = [];
Meteor.methods({
/**
* @summary Meteor method for submitting a flag from the client
* NOTE: the current user and the flag author user might sometimes be two different users!
* Required properties: title
* @memberof Flags
* @isMethod true
* @param {Object} flag - the flag being inserted
*/
'flags.new': function (flag) {
Flags.simpleSchema().namedContext("flags.new").validate(flag);
flag = Telescope.callbacks.run("flags.new.method", flag, Meteor.user());
if (Meteor.isServer && this.connection) {
flag.userIP = this.connection.clientAddress;
flag.userAgent = this.connection.httpHeaders["user-agent"];
}
flag.posts = [flag.lastPost];
return Flags.methods.new(flag);
},
/**
* @summary Meteor method for submitting a flag from the client
* NOTE: the current user and the flag author user might sometimes be two different users!
* Required properties: title
* @memberof Flags
* @isMethod true
* @param {Object} flag - the flag being inserted
*/
'flags.insertPost': function (flag) {
var item = Flags.findOne(flag._id);
flag = Telescope.callbacks.run("flags.insertPost.method", flag, Meteor.user());
update = {
$inc: {'postsCount': 1},
$addToSet: {posts: flag.lastPost},
};
var result = Flags.update({_id: item._id}, update);
if (result > 0) {
// --------------------- Server-Side Async Callbacks --------------------- //
return true;
}
},
/**
* @summary Meteor method for submitting a flag from the client
* NOTE: the current user and the flag author user might sometimes be two different users!
* Required properties: title
* @memberof Flags
* @isMethod true
* @param {Object} flag - the flag being inserted
*/
'flags.removePost': function (flag) {
var item = Flags.findOne(flag._id);
flag = Telescope.callbacks.run("flags.removePost.method", flag, Meteor.user());
update = {
$inc: {'postsCount': -1},
$pull: {posts: flag.lastPost},
};
var result = Flags.update({_id: item._id}, update);
if (result > 0) {
// --------------------- Server-Side Async Callbacks --------------------- //
return true;
}
},
/**
* @summary Meteor method for deleting a post
* @memberof Posts
* @isMethod true
* @param {String} flagId - the id of the post
*/
'flags.remove': function (flagId) {
check(flagId, String);
// remove flag comments
// if(!this.isSimulation) {
// Comments.remove({flag: flagId});
// }
// NOTE: actually, keep comments after all
var flag = Flags.findOne({_id: flagId});
// delete flag
Flags.remove(flagId);
Telescope.callbacks.runAsync("flags.remove.async", flag);
},
/**
* @summary Meteor method for deleting a post
* @memberof Flags
* @isMethod true
* @param {String} editedFlag - the id of the post
*/
'flags.editFlagName': function (editedFlag) {
modifier = {$set: {name: editedFlag.newName}};
const flagId = editedFlag._id;
Flags.simpleSchema().namedContext("flags.edit").validate(modifier, {modifier: true});
check(flagId, String);
const flag = Flags.findOne(flagId);
modifier = Telescope.callbacks.run("flags.edit.method", modifier, flag, Meteor.user());
return Flags.methods.edit(flagId, modifier, flag);
},
/**
* @summary Meteor method for deleting a post
* @memberof Flags
* @isMethod true
* @param {String} editedFlag - the id of the post
*/
'flags.editFlagDescription': function (editedFlag) {
modifier = {$set: {description: editedFlag.newDesctiption}};
const flagId = editedFlag._id;
Flags.simpleSchema().namedContext("flags.edit").validate(modifier, {modifier: true});
check(flagId, String);
const flag = Flags.findOne(flagId);
modifier = Telescope.callbacks.run("flags.edit.method", modifier, flag, Meteor.user());
return Flags.methods.edit(flagId, modifier, flag);
},
});
//Flags.smartMethods({
// createName: "flags.new",
// editName: "flags.edit"
//});
|
trujunzhang/politiclarticles
|
packages/nova-flags/lib/methods.js
|
JavaScript
|
mit
| 5,850 |
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/share.html'],
function(Backbone, Marionette, Mustache, $, template) {
return Marionette.ItemView.extend({
template: function(serialized_model) {
return Mustache.render(template, serialized_model);
},
events: {
'touchend': 'onTap',
'touchmove': 'onTouchMove'
},
initialize: function(options) {
var shareInfo = appConfig.share_info;
var hash = '';
if (options&&options.shareInfo) shareInfo = options.shareInfo;
if (options&&options.hash) hash = options.hash;
if (options&&options.originalShareInfo) this.originalShareInfo = options.originalShareInfo;
this.model = new Backbone.Model(shareInfo);
var self = this;
util.setWechatShare(shareInfo, function() {
self.destroy();
}, null, hash);
this.render();
},
onRender: function() {
$('body').append(this.$el);
$('.articleWrapper').addClass('blur');
},
onTap: function(ev) {
this.onDestroy();
util.preventDefault(ev);
util.stopPropagation(ev);
},
onTouchMove: function(ev) {
util.preventDefault(ev);
util.stopPropagation(ev);
},
onDestroy: function() {
if (this.originalShareInfo) util.setWechatShare(this.originalShareInfo);
this.stopListening();
this.$el.remove();
$('.articleWrapper').removeClass('blur');
},
className: 'shareWrapper shareOverlay overlay'
});
});
|
yoniji/ApeReaderDemo
|
app/scripts/common/share_view.js
|
JavaScript
|
mit
| 1,897 |
//import './quadraticBezier.js';
//import './qubicBezier.js';
import './bezierMotion.js';
|
aruns07/Playground
|
math/lesson19/main.js
|
JavaScript
|
mit
| 89 |
{
if (http2) {
return createHTTP2Server(benchmark);
} else {
return createHTTPServer();
}
}
|
stas-vilchik/bdd-ml
|
data/6142.js
|
JavaScript
|
mit
| 106 |
var notification = {
notify: function(args){
var project = args.project;
var project_event = args.project_event;
var internal = args.internal;
var current_time = args.current_time;
var message = args.message;
var author_id = args.author_id || '';
util.checkArgs(args, ["project", "project_event", "internal", "current_time", "message"]);
var notifiedEvent = notification_cache.isNotified(project_event);
if (notifiedEvent){
// Don't notify same event
return;
}
notification_cache.add(project_event);
var notification_id = notification_cache.cacheKey(project_event);
this.createNotification({
avatar_url: project.avatar_url,
notification_id: notification_id,
title: project.name,
message: message
});
// use hash of notification_id as unique id
project_event._id = notification_id;
project_event.project_name = project.name;
project_event.target_id = internal.target_id;
project_event.target_url = internal.target_url;
project_event.notified_at = current_time;
project_event.message = message;
project_event.author_id = author_id;
config.addNotifiedHistories([project_event]);
this.incNotificationCount();
},
createNotification: function(args){
var notification_id = args.notification_id;
var title = args.title;
var message = args.message;
util.checkArgs(args, ["notification_id", "title", "message"]);
chrome.notifications.create(
notification_id,
{
type: "basic",
iconUrl: args.avatar_url || "img/gitlab_logo_128.png",
title: title,
message: message,
priority: 0
},
function(){
// do nothing
}
);
},
incNotificationCount: function(){
this.notification_count ++;
chrome.browserAction.setBadgeText({text: String(this.notification_count)});
},
notification_count: 0
};
|
hotoo/chrome-gitlab-notifier
|
src/notification.js
|
JavaScript
|
mit
| 2,287 |
const path = require('path');
const rootPath = process.cwd();
const context = path.join(rootPath, "src");
const outputPath = path.join(rootPath, 'dist');
const bannerPlugin = require(path.join(__dirname, 'plugins', 'banner.js'));
module.exports = {
mode: 'development',
context: context,
entry: {
dicomParser: './index.js'
},
externals: {
'zlib': 'zlib'
},
node: false,
target: 'web',
output: {
filename: '[name].js',
library: {
commonjs: "dicom-parser",
amd: "dicom-parser",
root: 'dicomParser'
},
libraryTarget: 'umd',
globalObject: 'this',
path: outputPath,
umdNamedDefine: true
},
devtool: 'source-map',
module: {
rules: [{
enforce: 'pre',
test: /\.js$/,
exclude: /(node_modules|test)/,
loader: 'eslint-loader',
options: {
failOnError: false
}
}, {
test: /\.js$/,
exclude: /(node_modules)/,
use: [{
loader: 'babel-loader'
}]
}]
},
plugins: [
bannerPlugin()
]
};
|
yagni/dicomParser
|
config/webpack/webpack-base.js
|
JavaScript
|
mit
| 1,043 |
class ConfigStore {
baseServicePath = '';
monthHours = {"January":744, "February":1416, "March":2160, "April":2880, "May":3624, "June":4344,
"July":5088, "August":5832, "September":6552, "October":7296, "November":8016, "December":8760};
mHours = [744,1416,2160,2880,3624,4344,5088,5832,6552,7296,8016,8760];
mDays = [32,60,91,121,152,182,213,244,274,305,335,365];
monthDays = {"January":32, "February":60, "March":91, "April":121, "May":152, "June":182,
"July":213, "August":244, "September":274, "October":305, "November":335, "December":365};
hours = ["00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00",
"11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"];
activeKD = 0;
//TODO - for now we just have munich - maybe need to think of a different format based on how many we will have
KDValues = [[518,440,446,315,128,45,0,0,127,308,347,397],
[518,440,446,315,128,45,0,0,127,308,347,397]
];
//sometimes we have elements to which we need to create random indexes so we could reference them
//for instance with all our graphs, we sometimes reference html from js and for that we need
//unique ids. Here just using a very simple index, one for all elements, which is more tha what we need
//but probably not going to run ot of numbers anytime soon
curRandKey = 10;
constructor(){
}
getNextKey(){
return ++this.curRandKey;
}
}
export default new ConfigStore;
|
boris-p/borispl
|
app/stores/ConfigStore.js
|
JavaScript
|
mit
| 1,606 |
{
return (() => object.arguments).call();
}
|
stas-vilchik/bdd-ml
|
data/2298.js
|
JavaScript
|
mit
| 46 |
//// If the app loads with an empty db, fill it with a starting set of data.
import { Meteor } from 'meteor/meteor';
import { Messages } from '../../api/messages/define-messages.js';
import { Rooms } from '../../api/rooms/define-rooms.js';
Meteor.startup( () => {
// Messages.remove({});
// Rooms.remove({});
if (
0 !== Messages.find().count()
|| 0 !== Rooms.find().count()
) { return; }
let timestamp = (new Date()).getTime();
([
{ name:'Lounge' , secretInfo:'Admin only!', messages:['Hi!', 'Relaxing!'] },
{ name:'Kitchen', secretInfo:123 , messages:['Hi!', 'Cooking!'] },
]).forEach( (room) => {
const roomId = Rooms.insert({
name: room.name,
secretInfo: room.secretInfo,
});
room.messages.forEach( (text) => {
Messages.insert({
roomId: roomId,
text: text,
createdAt: new Date(timestamp),
});
});
timestamp += 1; // ensure unique timestamp
});
});
|
richplastow/datagrater-demo-1
|
imports/startup/server/fixtures.js
|
JavaScript
|
mit
| 985 |
import React from 'react';
import { Link } from 'react-router-dom';
import { shallowWithIntl } from '../../../../../../utils/testUtils';
import { UnconnectedResourceInfo as ResourceInfo, selector } from '../ResourceInfoContainer';
import UnpublishedLabel from '../../../../../label/unpublished/UnpublishedLabel';
function getState() {
return {
data: {
resources: {
123456: {
id: '123456',
name: { fi: 'Resource Name' },
extra: 'attribute',
isFavorite: false,
peopleCapacity: 9,
public: true,
unitName: '',
},
},
},
};
}
describe('shared/availability-view/ResourceInfoContainer', () => {
function getWrapper(props) {
const defaults = {
date: '2017-01-02',
id: 'r-1',
isFavorite: false,
isSelected: false,
name: 'Resource name',
peopleCapacity: 19,
public: true,
unitName: '',
};
return shallowWithIntl(<ResourceInfo {...defaults} {...props} />);
}
test('renders a div.resource-info', () => {
const wrapper = getWrapper();
expect(wrapper.is('div.resource-info')).toBe(true);
});
test('has selected class if isSelected', () => {
const wrapper = getWrapper({ isSelected: true });
expect(wrapper.is('.resource-info-selected')).toBe(true);
});
test('renders the name and link to resource page', () => {
const date = '2017-02-03';
const link = getWrapper({ date, id: 'r-1', name: 'Room 1' }).find(Link);
expect(link).toHaveLength(1);
expect(link.prop('to')).toBe(`/resources/r-1?date=${date}`);
expect(link.prop('children')).toBe('Room 1');
});
test('renders the capacity in details', () => {
const details = getWrapper({ peopleCapacity: 3 }).find('.details');
expect(details).toHaveLength(1);
expect(details.text()).toContain('3');
});
test('renders unpublished label if public is false', () => {
const label = getWrapper({ public: false }).find(UnpublishedLabel);
expect(label).toHaveLength(1);
});
test('does not render unpublished label if public is true', () => {
const label = getWrapper({ public: true }).find(UnpublishedLabel);
expect(label).toHaveLength(0);
});
describe('selector', () => {
function getSelected(props) {
const defaults = { id: '123456' };
return selector()(getState(), { ...defaults, ...props });
}
test('returns resource info', () => {
const actual = getSelected();
expect(actual).toEqual({
name: 'Resource Name',
peopleCapacity: 9,
public: true,
unitName: '',
});
});
});
});
|
fastmonkeys/respa-ui
|
app/shared/availability-view/sidebar/group-info/resource-info/__tests__/ResourceInfoContainer.test.js
|
JavaScript
|
mit
| 2,652 |
var gulp = require('gulp');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
var concat = require('gulp-concat');
var webserver = require('gulp-webserver');
var del = require('del');
var header = require('gulp-header');
var uglify = require('gulp-uglify');
var babel = require('gulp-babel'); // Uglify not working without gulp-babel?
var rename = require('gulp-rename');
var minifyHtml = require('gulp-minify-html');
var pkg = require('./package.json');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
// Develop build
// ============================================================================
gulp.task('sass', function() {
return gulp.src('src/scss/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(sourcemaps.write())
.pipe(rename('elasticslider.css'))
.pipe(gulp.dest('src/css'));
});
gulp.task('js', function () {
gulp.src([
'src/elastic-slider/elastic-slider.js',
'src/elastic-slider-pagi-item/elastic-slider-pagi-item.js',
]);
});
gulp.task('watch', function () {
gulp.watch('src/scss/**/*.scss', ['sass']);
gulp.watch('src/**/*.js', ['js']);
});
gulp.task('webserver', () => {
return gulp.src('./src')
.pipe(webserver({
livereload: false,
fallback: 'demo.html',
port: 5000,
open: true,
}));
});
// Dist build
// ============================================================================
gulp.task('dist:clean', function (cb) {
return del(['dist'], cb);
});
gulp.task('dist:copyView', ['dist:clean'], function () {
return gulp.src([
'src/elastic-slider/*.html',
'src/elastic-slider-pagi-item/*.html',
])
.pipe(concat('polymer-elastic-slider.html'))
.pipe(minifyHtml({
quotes: true,
empty: true,
spare: true
}))
.pipe(gulp.dest('dist'));
});
gulp.task('dist:sass', function() {
return gulp.src('src/scss/*.scss')
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(rename('elasticslider.css'))
.pipe(header(banner, { pkg : pkg } ))
.pipe(gulp.dest('dist/css'));
});
gulp.task('dist:build', ['dist:clean'], function () {
return gulp.src([
'src/elastic-slider/*.js',
'src/elastic-slider-pagi-item/*.js',
])
.pipe(concat('polymer-elastic-slider.min.js'))
.pipe(babel({
presets: ['es2015']
}))
.pipe(uglify())
.pipe(header(banner, { pkg : pkg } ))
.pipe(gulp.dest('dist'))
});
// Tasks
// ============================================================================
gulp.task('serve', ['sass', 'js', 'webserver', 'watch']);
gulp.task('default', ['dist:build', 'dist:copyView', 'dist:sass']);
|
JamyGolden/Polymer-ElasticSlider
|
gulpfile.js
|
JavaScript
|
mit
| 3,047 |
var Dam = Dam || {};
(function(){
'use strict';
Dam.Resource = (function() {
var publicMethods = {
init: init
};
function bindPeopleOptionCheckboxClick () {
var showConsent;
var people = $('#dam-people-container').children('.collection-check-box').children(':checkbox')
showConsent = people.toArray().some(function(p){
return $(p).is(':checked');
});
toggleConsentFormInputs(showConsent);
$(people).on('click', function(e){
showConsent = people.toArray().some(function(p){
return $(p).is(':checked');
});
toggleConsentFormInputs(showConsent);
});
}
function toggleConsentFormInputs (showConsent) {
var isConsent, consentFile;
consentFile = $("input[name='dam_resource[consent_file]']");
if (showConsent) {
consentFile.parent().show()
consentFormRequired();
} else {
consentFile.parent().hide()
consentFormInessential()
}
}
function consentFormInessential () {
$('button[value="submit_to_approval"]').attr('disabled', false)
}
function consentFormRequired () {
var approvalSubmit = $('button[value="submit_to_approval"]').attr('disabled', false)
var consentFileLink = $('#consent_file_download_link');
var consentFileInput = $("input[name='dam_resource[consent_file]']");
// checks if the consent dosent form exist as a link
// and form is visible. if so the save buttons are diabled
if (consentFileLink.attr('href') == null && consentFileInput.is(':visible')) {
approvalSubmit.attr('disabled', true);
}
consentFileInput.change(function(e){
var submitDisabled = true;
submitDisabled = !(this.files.length == 1)
approvalSubmit.attr('disabled', submitDisabled);
});
}
function init () {
bindPeopleOptionCheckboxClick();
}
return publicMethods;
});
})();
|
boost/dam_uploader
|
app/assets/javascripts/dam_resource.js
|
JavaScript
|
mit
| 1,988 |
const genguobuquPattern = require('./genguobuquPattern');
const {
assertAllExamplesMatch,
assertNoneMatch,
findLocsRegex,
parseSentence,
} = require('../lib/testUtils');
test('matches all examples', async () => {
await assertAllExamplesMatch(genguobuquPattern);
});
test('sentence where 过不去 parses as 3 separate tokens', async () => {
const sentence = await parseSentence('别跟你的爸爸过不去。');
expect(genguobuquPattern.match(sentence)).toEqual(
findLocsRegex(sentence, '(跟).*(过不去)')
);
});
test('sentence where 过不去 parses as 1 token', async () => {
const sentence = await parseSentence('这是跟我过不去。');
expect(genguobuquPattern.match(sentence)).toEqual(
findLocsRegex(sentence, '(跟).*(过不去)')
);
});
test('sentence with a person name', async () => {
const sentence = await parseSentence('这是跟查尔斯过不去。');
expect(genguobuquPattern.match(sentence)).toEqual(
findLocsRegex(sentence, '(跟).*(过不去)')
);
});
test('sentence with a type of person', async () => {
const sentence = await parseSentence('这是跟爸爸过不去。');
expect(genguobuquPattern.match(sentence)).toEqual(
findLocsRegex(sentence, '(跟).*(过不去)')
);
});
test("doesn't match negative examples", async () => {
await assertNoneMatch(genguobuquPattern, [
'我们大概去了,不过要看天气怎么样再决定',
'不要担心过去。',
'也许他不回去过春节。',
]);
});
|
chanind/cn-grammar-matcher
|
src/patterns/genguobuquPattern.test.js
|
JavaScript
|
mit
| 1,501 |
/*global
io: false,
Thywill: false
*/
/**
* @fileOverview
* Client ApplicationInterface definition.
*/
(function () {
'use strict';
/**
* @class
* Applications must implement a child class of Thywill.ApplicationInterface
* in their client code.
*
* Many of the methods in this class are invoked by Thywill as a result of
* messages received from the server or other circumstances, such as
* connection and disconnection.
*
* Additionally, an instance of Thywill.ApplicationInterface will emit events
* corresponding to these function calls:
*
* connected
* connecting
* connectionFailure
* disconnected
* received
*
* The last event in the list is an arriving message, the others notices of
* connection state.
*
* @param {string} applicationId
* The unique ID for this application.
*/
Thywill.ApplicationInterface = function SocketIoApplicationInterface (applicationId) {
Thywill.ApplicationInterface.super_.call(this);
this.applicationId = applicationId;
// Listen for traffic. These are separate functions to allow for easier
// overriding in child classes.
this._listenForConnected();
this._listenForConnectionFailure();
this._listenForConnecting();
this._listenForDisconnected();
this._listenForReceived();
};
Thywill.inherits(Thywill.ApplicationInterface, io.EventEmitter);
var p = Thywill.ApplicationInterface.prototype;
//------------------------------------
// Methods: initialization.
//------------------------------------
p._listenForConnected = function () {
var self = this;
// Initial connection succeeds.
Thywill.on('connected', function () {
self.connected();
self.emit('connected');
});
};
p._listenForConnectionFailure = function () {
var self = this;
// Initial connection failed with timeout.
Thywill.on('connectionFailure', function() {
self.connectionFailure();
self.emit('connectionFailure');
});
};
p._listenForConnecting = function () {
var self = this;
// Client is trying to connect or reconnect.
Thywill.on('connecting', function (transport_type) {
self.connecting();
self.emit('connecting');
});
};
p._listenForDisconnected = function () {
var self = this;
// Client is disconnected.
Thywill.on('disconnected', function () {
self.disconnected();
self.emit('disconnected');
});
};
p._listenForReceived = function () {
var self = this;
// Message received from the server.
Thywill.on('received', function (applicationId, message) {
if (applicationId !== self.applicationId) {
return;
}
self.received(message);
self.emit('received', message);
});
};
//------------------------------------
// Methods.
//------------------------------------
/**
* Send a Thywill.Message object to the server.
*
* @param {mixed|Thywill.Message} message
* Any data or a Thywill.Message instance
*/
p.send = function (message) {
if (!(message instanceof Thywill.Message)) {
message = new Thywill.Message(message);
}
Thywill.send(this.applicationId, message);
};
/**
* Invoked when a message is received from the server.
*
* @param {Thywill.Message} message
* A Thywill.Message instance.
*/
p.received = function (message) {};
/**
* Invoked when the client is trying to connect or reconnect.
*/
p.connecting = function () {};
/**
* Invoked when the client successfully connects or reconnects after
* disconnection.
*/
p.connected = function () {};
/**
* Invoked when the client fails to initially connect or fails to reconnect
* after disconnection.
*/
p.connectionFailure = function () {};
/**
* Invoked when the client is unexpectedly disconnected. This should usually
* only happen due to network issues, server shutting down, etc.
*/
p.disconnected = function () {};
})();
|
exratione/thywill
|
core/client/socketIoClientInterface/socketIoApplicationInterface.js
|
JavaScript
|
mit
| 4,027 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define("require exports ../core/tsSupport/declareExtendsHelper ../core/tsSupport/decorateHelper ../core/Accessor ../core/Collection ../core/collectionUtils ../core/Logger ../core/promiseUtils ../core/accessorSupport/decorators ../layers/Layer".split(" "),function(w,x,p,k,q,r,l,t,u,f,m){function g(e,d,a){for(var b,c=0,v=e.length;c<v;c++)if(b=e.getItemAt(c),b[d]===a||b&&null!=b.layers&&(b=g(b.layers,d,a)))return b}var h=r.ofType(m),n=t.getLogger("esri.support.LayersMixin");return function(e){function d(a){var b=
e.call(this,a)||this;b.layers=new h;b.layers.on("after-add",function(c){c=c.item;c.parent&&c.parent!==b&&"remove"in c.parent&&c.parent.remove(c);c.parent=b;b.layerAdded(c);"elevation"===c.type&&n.error("Layer '"+c.title+", id:"+c.id+"' of type '"+c.type+"' is not supported as an operational layer and will therefore be ignored.")});b.layers.on("after-remove",function(c){c=c.item;c.parent=null;b.layerRemoved(c)});return b}p(d,e);d.prototype.destroy=function(){this.layers.drain(this.layerRemoved,this)};
Object.defineProperty(d.prototype,"layers",{set:function(a){this._set("layers",l.referenceSetter(a,this._get("layers"),h))},enumerable:!0,configurable:!0});d.prototype.findLayerById=function(a){return g(this.layers,"id",a)};d.prototype.add=function(a,b){var c=this,d=this.layers;b=d.getNextIndex(b);u.isThenable(a)?a.then(function(a){c.destroyed||(a instanceof m?d.add(a,b):n.error("#add()","Promise did not resolve with a valid layer."))}):a.parent===this?this.reorder(a,b):d.add(a,b)};d.prototype.addMany=
function(a,b){var c=this,d=this.layers;b=d.getNextIndex(b);a.slice().forEach(function(a){a.parent===c?c.reorder(a,b):(d.add(a,b),b+=1)})};d.prototype.findLayerByUid=function(a){return g(this.layers,"uid",a)};d.prototype.remove=function(a){return this.layers.remove(a)};d.prototype.removeMany=function(a){return this.layers.removeMany(a)};d.prototype.removeAll=function(){return this.layers.removeAll()};d.prototype.reorder=function(a,b){return this.layers.reorder(a,b)};d.prototype.layerAdded=function(a){};
d.prototype.layerRemoved=function(a){};k([f.property({type:h,cast:l.castForReferenceSetter})],d.prototype,"layers",null);return d=k([f.subclass("esri.support.LayersMixin")],d)}(f.declared(q))});
|
ycabon/presentations
|
2018-user-conference/arcgis-js-api-road-ahead/demos/gamepad/api-snapshot/esri/support/LayersMixin.js
|
JavaScript
|
mit
| 2,388 |
'use strict';
var express = require('express'),
router = express.Router(),
async = require('async'),
experience = require("../models/experience"),
project = require("../models/project"),
competence = require("../models/competence");
/**
* GET /profile
*/
router.get('/', function (request, response) {
async.parallel({
experiences: function (callback) {
experience.findAll(callback);
},
projects: function (callback) {
project.findAll(callback);
},
competences: function (callback) {
competence.findAll(callback);
}
}, function (errs, results) {
if (errs) {
response.status(404).end();
} else {
response.render('profile/index', {
isProfile : true,
experiences: results.experiences,
projects : results.projects,
competences: results.competences
});
}
});
});
/**
*
*/
module.exports = function (app) {
app.use('/profile', router);
};
|
abachar/website
|
routes/profile.js
|
JavaScript
|
mit
| 1,102 |
'use strict';
var app = angular.module('mean.taskinsert');
app.controller('TaskInsertController',
['Global', 'TaskInsertService', '$http', function (Global, TaskInsertService, $http) {
var vm = this;
// Init task
vm.task = {
dependencies: []
};
this.strings = Global.tasklist.strings;
/**
* Create a new task
* @param valid
*/
this.create = function (valid) {
var defer = TaskInsertService.create(valid, vm.task);
defer.then(function () {
vm.task.title = '';
vm.task.assigned = '';
vm.task.estimate = '';
vm.task.dependenciesText = '';
vm.task.dependencies = [];
vm.task.content = '';
}, function (error) {
console.log('error: ' + error);
// TODO Display error to user
});
};
/**
* Query tasks for dependencies
* @param query
* @returns {*}
*/
vm.queryTasks = function (query) {
var getQuery = $http.get('/queryTasklist/' + query);
return getQuery;
};
/**
* Link function on dependency being set
* @param dependency
*/
vm.dependencySet = function (dependency) {
vm.task.dependencies.push(dependency._id);
};
}]);
|
loganetherton/ac
|
packages/custom/taskinsert/public/controllers/TaskInsertController.js
|
JavaScript
|
mit
| 1,284 |
module.exports = {
'env': {
'es6': false
},
'ecmaFeatures': {
'arrowFunctions': true,
'blockBindings': true,
'classes': true,
'defaultParams': true,
'destructuring': true,
'forOf': true,
'generators': false,
'modules': true,
'objectLiteralComputedProperties': true,
'objectLiteralDuplicateProperties': false,
'objectLiteralShorthandMethods': true,
'objectLiteralShorthandProperties': true,
'restParams': true,
'spread': true,
'superInFunctions': true,
'templateStrings': true,
'jsx': true
},
'rules': {
// enforces no braces where they can be omitted
// http://eslint.org/docs/rules/arrow-body-style
'arrow-body-style': [2, 'as-needed'],
// require parens in arrow function arguments
'arrow-parens': 0,
// require space before/after arrow function's arrow
// https://github.com/eslint/eslint/blob/master/docs/rules/arrow-spacing.md
'arrow-spacing': [2, { 'before': true, 'after': true }],
// verify super() callings in constructors
'constructor-super': 0,
// enforce the spacing around the * in generator functions
'generator-star-spacing': 0,
// disallow modifying variables of class declarations
'no-class-assign': 0,
// disallow modifying variables that are declared using const
'no-const-assign': 2,
// disallow to use this/super before super() calling in constructors.
'no-this-before-super': 0,
// require let or const instead of var
'no-var': 2,
// require method and property shorthand syntax for object literals
// https://github.com/eslint/eslint/blob/master/docs/rules/object-shorthand.md
'object-shorthand': [2, 'always'],
// suggest using arrow functions as callbacks
'prefer-arrow-callback': 2,
// suggest using of const declaration for variables that are never modified after declared
'prefer-const': 2,
// suggest using the spread operator instead of .apply()
'prefer-spread': 0,
// suggest using Reflect methods where applicable
'prefer-reflect': 0,
// suggest using template literals instead of string concatenation
// http://eslint.org/docs/rules/prefer-template
'prefer-template': 2,
// disallow generator functions that do not have yield
'require-yield': 0
}
};
|
5punk/isomorphic-style-loader
|
node_modules/eslint-config-airbnb/rules/es6.js
|
JavaScript
|
mit
| 2,311 |
import React, { Component } from 'react';
import { Grid, Row, Col, FormGroup,
FormControl, HelpBlock, ControlLabel } from 'react-bootstrap';
import DialPad from './DialPad';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
number: ''
};
}
render() {
return (
<div>
<Grid>
<Row className="show-grid">
<Col xs={12} md={8}>
<form>
<FormGroup
controlId="formBasicText"
validationState={() => {}}
>
<ControlLabel><p>Type your phone number</p></ControlLabel>
<FormControl
type="text"
value={this.state.number}
placeholder=""
onChange={() => {}}
/>
<FormControl.Feedback />
<HelpBlock><p>Then press next</p></HelpBlock>
</FormGroup>
</form>
</Col>
<Col xs={12} md={4}>
<DialPad
onClick={(e) => { this.setState({ number: this.state.number + e.toString() }); }}
onBackClick={() => { this.setState({ number: this.state.number.slice(0, -1) }); }}
/>
</Col>
</Row>
</Grid>
</div>
);
}
}
|
geekmansam/Olive-Check-In
|
app/components/Home.js
|
JavaScript
|
mit
| 1,397 |
QUnit.test( 'filter predicate', assert => {
var it = Iterator.from([1,2,3])
var a = it.filter(i=>i>2).toArray()
assert.equal(a[0],3)
})
QUnit.test( 'filter object', assert => {
var it = Iterator.of({a:1,b:2},{a:3,b:5},{a:1,b:9})
var a = it.filter({a:1}).toArray()
assert.equal(a[0].b,2)
assert.equal(a[1].b,9)
})
QUnit.test('filter regex', assert=>{
var it = Iterator.of("ciao","miao","caio")
var a = it.filter(/c.*o/).toArray()
assert.equal(a[0],'ciao')
assert.equal(a[1],'caio')
})
|
PaoloSarti/Iterator.js
|
test/filter-test.js
|
JavaScript
|
mit
| 529 |
/**
* @project MOOTOMBO!WebOS
* @subProject MFW - A PHP, Javascript and CSS Framework
*
* @package MFW.library
* @subPackage Librarie
* @version 1.0
*
* @author devXive - research and development <support@devxive.com> (http://www.devxive.com)
* @copyright Copyright (C) 1997 - 2013 devXive - research and development. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @assetsLicense devXive Proprietary Use License (http://www.devxive.com/license)
*/
// Initialize Core Objects
MFW = {};
MFW.web = {};
MFW.system = {};
MFW.filesAdded = ''; //List of files added by loadJsCssFile() in the form "[filename1],[filename2],etc"
// Set Variables and Objects
MFW.web.online = navigator.onLine;
MFW.web.location = location.protocol;
/* #####################
* # Load JS/CSS Files #
* #####################
*/
/*
* Function to dynamically loading external JavaScript and CSS files
*
* To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "SCRIPT" or "LINK" element,
* assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree.
* It sounds a lot more fancy than it really is. Lets see how it all comes together:
*
* Example:
* loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
* loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
* loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
*
* Based on: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
*/
function loadJsCssFile(filename, filetype, debug) {
// Check first if we already have this file in space
if (MFW.filesAdded.indexOf("[" + filename + "]") == -1) {
MFW.filesAdded += "[" + filename + "]";
// If filename is an external JavaScript file
if (filetype === "js")
{
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
// If filename is an external CSS file
else if (filetype === "css")
{
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (typeof fileref != "undefined")
{
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
else
{
if (debug)
{
console.log("File already added: " + filename);
}
}
}
/* ################
* # AJAX SECTION #
* ################
*/
/*
* Function to save data via ajax and the PHP Class MRDKDatabase::save() Method
*
* @param url string URL or Link to save the request
* @param data object The data object (Should contain the structure of the database tables/rows)
* data: {
* table: 'name_without_prefix',
* where: {
* col: 'value'
* }
* }
*
* First: The method check available columns and build the array to store the data. Cols that does not exist, are ignored
* Second: Checks if the appropriate entry exist
* => If exist : throw an update
* => If not exist: throw an insert
* => If its empty: throw an update // TODO: May need an overhaul because if all is empty we can also delete them?!
*/
function MFWSave(url, data) {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data,
headers: {'X-Requested-With': 'XMKHttpRequest'},
success: function( responseData, textStatus, jqXHR ) {
var mSuccess = {};
mSuccess.status = true;
mSuccess.data = responseData,
mSuccess.text = textStatus,
mSuccess.xhr = jqXHR;
return mSuccess;
},
error: function( responseData, textStatus, errorThrown ) {
var mError = {};
mError.status = false;
mError.data = responseData,
mError.text = textStatus,
mError.xhr = errorThrown;
return mError;
}
});
}
/*
* Function to read data via ajax and the PHP Class MFWDatabase::select() Method ( Simple usage )
*
* @param url string URL or Link to save the request
* @param data object The data object (Should contain the structure of the database tables/rows)
* data: {
* table: 'name_without_prefix',
* where: {
* col1: 'value1',
* col2: 'value2',
* col3: 'value3'
* }
* }
*/
function MFWSelect(url, data) {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data,
headers: {'X-Requested-With': 'XMKHttpRequest'},
success: function( responseData, textStatus, jqXHR ) {
var mSuccess = {};
mSuccess.status = true;
mSuccess.data = responseData,
mSuccess.text = textStatus,
mSuccess.xhr = jqXHR;
return mSuccess;
},
error: function( responseData, textStatus, errorThrown ) {
var mError = {};
mError.status = false;
mError.data = responseData,
mError.text = textStatus,
mError.xhr = errorThrown;
return mError;
}
});
}
/*
* Function to remove data via ajax and the PHP Class MFWDatabase::select() Method ( Simple usage )
*
* @param url string URL or Link to save the request
* @param data object The data object (Should contain the structure of the database tables/rows)
* data: {
* table: 'name_without_prefix',
* where: {
* id: 'id'
* }
* }
*/
function MFWRemove(url, data) {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data,
headers: {'X-Requested-With': 'XMKHttpRequest'},
success: function( responseData, textStatus, jqXHR ) {
var mSuccess = {};
mSuccess.status = true;
mSuccess.data = responseData,
mSuccess.text = textStatus,
mSuccess.xhr = jqXHR;
return mSuccess;
},
error: function( responseData, textStatus, errorThrown ) {
var mError = {};
mError.status = false;
mError.data = responseData,
mError.text = textStatus,
mError.xhr = errorThrown;
return mError;
}
});
}
|
mootombo/Framework
|
src/libraries/lib_mootombo/media/js/core/mfw.js
|
JavaScript
|
mit
| 6,903 |
'use strict'
var q = require('q')
var api = require('../api')
var config = require('../config')
var userInput = require('../user-input')
module.exports = createIssue
// Get required meta data to create issues
function getMetaData () {
return api.apiRequest('/issue/createmeta')
}
function reloadMetaData () {
return getMetaData()
.then((meta) => {
var result = {}
// Populate projects, keys and their respective issue types
for (var index in meta.projects) {
let p = meta.projects[index]
result[p.key] = {
id: p.id,
name: p.name,
issuetypes: p.issuetypes
}
}
return config.updateDB({projects: result})
})
}
function getProjectMap () {
var projects = config.getState().projects
return Object.keys(projects)
.map((key) => {
return {
value: key,
name: projects[key].name
}
})
}
function getIssueTypeMap (projectKey) {
return config.getState().projects[projectKey]
.issuetypes
.map(function (type) {
return {
value: type.id,
name: type.name
}
})
}
function resolveIssueType (projectKey, type) {
// If we were passed an ID, return it
if (!isNaN(type)) {
return type
} else {
var lowerType = type.toLowerCase()
// Else, look for the issue type supplied in the project's metadata
var match = config.getState().projects[projectKey].issuetypes.find((item) => {
return item.name.toLowerCase() === lowerType
})
if (!match) {
throw new TypeError('Invalid issue type: ', type)
}
return match.id
}
}
// API Docs: https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue
function createIssue (program) {
var issue = {}
program = program || {}
return reloadMetaData()
.then(() => {
// Only ask for project if it's not supplied
var projectPromise = program.project
? q.when(program.project)
: userInput.askQuestion('Project', 'list', getProjectMap())
return projectPromise
})
.then((projectKey) => {
issue.projectKey = projectKey
// Only ask for issue type if it's not supplied
return program.issueType
? q.when(resolveIssueType(projectKey, program.issueType))
: userInput.askQuestion('Issue Type', 'list', getIssueTypeMap(projectKey))
})
.then((issueTypeId) => {
issue.issueTypeId = issueTypeId
return program.summary ? q.when(program.summary) : userInput.askQuestion('Issue Title')
})
.then((summary) => {
issue.summary = summary
if (program.skipDescription) {
return null
} else if (program.description) {
return program.description
} else {
return userInput.askQuestion('Description', 'editor')
}
})
.then((description) => {
// Create issue object with required fields
var newIssue = {
fields: {
project: {
key: issue.projectKey
},
summary: issue.summary,
issuetype: {
id: issue.issueTypeId
}
}
}
if (description) {
newIssue.fields.description = description
}
// Add optional fields
if (program.labels) {
newIssue.fields.labels = program.labels.split(',')
}
if (program.assignee) {
newIssue.fields.assignee = {
// if user specifies `me`, assign to themselves
name: program.assignee === 'me' ? config.getState().username : program.assignee
}
}
return api
.getClient()
.addNewIssue(newIssue)
})
}
|
goldcaddy77/jicli
|
lib/issues/create.js
|
JavaScript
|
mit
| 3,655 |
version https://git-lfs.github.com/spec/v1
oid sha256:07502af9f046b0b8956b9caec4ae86f6b8849116fc6ca6e3aca052e0d13765a8
size 914
|
yogeshsaroya/new-cdnjs
|
ajax/libs/yui/3.15.0/datatype-date-format/lang/datatype-date-format_vi-VN.js
|
JavaScript
|
mit
| 128 |
this.isAdmin = false;
hide('isAdmin');
hide('password');
require('crypto').randomBytes(24, function(err, buffer) {
var token = buffer.toString('hex');
dpd.email.post({
to : this.email,
subject : 'Beacon Mapper registration',
text : [
this.username,
'',
'Thank you for registering for Beacon Mapper!',
'Your API key:',
token
].join('\n')
}, function ( err, results ) {
if(!err){
this.key = token;
}
});
});
this.createdAt = Date.now();
|
Drak29/Beacon-Map
|
resources/users/post.js
|
JavaScript
|
mit
| 505 |
search_result['1967']=["topic_00000000000004C4_events--.html","PhoneNumberHelper Events",""];
|
asiboro/asiboro.github.io
|
vsdoc/search--/s_1967.js
|
JavaScript
|
mit
| 93 |
'use strict';
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('../webpack.config');
new WebpackDevServer(webpack(config), {
contentBase: __dirname,
hot: true,
stats: {
colors: true,
}
}).listen(config.port, config.ip, function (err) {
if (err) {
console.log(err);
}
console.log('Listening at ' + config.ip + ':' + config.port);
});
|
whoisandie/react-player
|
scripts/server.js
|
JavaScript
|
mit
| 418 |
"use strict";
module.exports = core => {
return (query, params = {}) => {
if (typeof name !== "string") {
throw new TypeError(`Invalid query ${query}`);
}
return new Promise((resolve, reject) => {
core.emit(query, params, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
};
};
|
metao1/chat
|
lib/promised-query.js
|
JavaScript
|
mit
| 344 |
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('pixel-peru', 'Unit | Component | pixel peru', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true
});
test('it renders', function(assert) {
assert.expect(2);
// Creates the component instance
var component = this.subject();
assert.equal(component._state, 'preRender');
// Renders the component to the page
this.render();
assert.equal(component._state, 'inDOM');
});
|
Goblab/observatorio-electoral
|
front/tests/unit/components/pixel-peru-test.js
|
JavaScript
|
mit
| 529 |
/* global describe, it */
var app = require('../app/index');
var request = require('supertest').agent(app.listen());
describe('GET /', function () {
it('status code should be 200', function (done) {
request
.get('/')
.expect(200, done);
});
});
describe('GET user id from params', function () {
it('should display "1024"', function (done) {
request
.get('/users/1024')
.expect('1024', done);
});
});
describe('GET static file', function () {
it('status code should be 200', function (done) {
request
.get('/notice.html')
.expect(200, done);
});
});
|
hiwanz/pikachu
|
test/test.js
|
JavaScript
|
mit
| 612 |
function add(x, y) {
return x + y;
}
exports.add = add
|
leoduran/hello-docker
|
app/calculator.js
|
JavaScript
|
mit
| 58 |
#!/usr/bin/env node
var shell = require('shelljs');
var fs = require('fs');
var path = require('path');
exports.copyDirWithoutFilesSyncRecursive = function(srcDir, dstDir) {
if(!shell.test('-e', srcDir)) {
throw new Error("srcDir Not Found!");
}
if(!shell.test('-e', dstDir)) {
shell.mkdir('-p', dstDir);
}
var folders = shell.find(srcDir).filter(function(file) {
if( !fs.statSync(file).isDirectory() ) {
return false;
}
var fileRelativePath = path.relative(srcDir, file);
var targetDir = path.join(dstDir, fileRelativePath);
shell.mkdir('-p', targetDir);
return true;
});
};
exports.emtpyDirSyncRecursive = function(dir) {
if(!shell.test('-e', dir)) {
throw new Error("dir Not Found!");
}
var itemsDeleted = shell.ls(dir).filter(function(file) {
var filePath = path.join(dir, file);
if( fs.statSync(filePath).isDirectory() ) {
shell.rm('-rf', filePath);
return true;
}
shell.rm('-f', filePath);
return true;
});
};
function copyOrMoveFilesSyncRecursive(srcDir, dstDir, action) {
if(!shell.test('-e', srcDir)) {
throw new Error("srcDir Not Found!");
}
if(!shell.test('-e', dstDir)) {
shell.mkdir('-p', dstDir);
}
var folders = shell.find(srcDir).filter(function(file) {
if( fs.statSync(file).isDirectory() ) {
return false;
}
var fileRelativePath = path.relative(srcDir, file);
var targetPath = path.join(dstDir, fileRelativePath);
var targetDir = path.dirname(targetPath);
if(!shell.test('-e', targetDir)) {
shell.mkdir('-p', targetDir);
}
action('-f', file, targetPath);
return true;
});
};
exports.copyFilesSyncRecursive = function(srcDir, dstDir) {
return copyOrMoveFilesSyncRecursive(srcDir, dstDir, shell.cp);
};
exports.moveFilesSyncRecursive = function(srcDir, dstDir) {
return copyOrMoveFilesSyncRecursive(srcDir, dstDir, shell.mv);
};
|
andromedarabbit/toolbox-js
|
lib/filesystem.js
|
JavaScript
|
mit
| 1,868 |
/*
*
* Example constants
*
*/
export const DEFAULT_ACTION = 'app/Example/DEFAULT_ACTION';
export const CALL_API = 'boilerplate/Example/CALL_API';
export const CALL_API_SUCCESS = 'boilerplate/Example/CALL_API_SUCCESS';
export const CALL_API_ERROR = 'boilerplate/Example/CALL_API_ERROR';
export const DEFAULT_LOCALE = 'en';
|
Jonathan-Steinmann/react-boilerplate-testing
|
app/containers/Example/constants.js
|
JavaScript
|
mit
| 327 |
'use strict';
describe('KiwiWebApi', function () {
it('contains spec with expectation', function () {
expect(true).toBe(true);
});
});
|
juanmarinbear/kiwi-web
|
src/components/kiwiwebapi/kiwiwebapi-service_test.js
|
JavaScript
|
mit
| 144 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.concatAST = concatAST;
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
/**
* Provided a collection of ASTs, presumably each from different files,
* concatenate the ASTs together into batched AST, useful for validating many
* GraphQL source files which together represent one conceptual application.
*/
function concatAST(asts) {
var batchDefinitions = [];
for (var i = 0; i < asts.length; i++) {
var definitions = asts[i].definitions;
for (var j = 0; j < definitions.length; j++) {
batchDefinitions.push(definitions[j]);
}
}
return {
kind: 'Document',
definitions: batchDefinitions
};
}
|
AntonyThorpe/knockout-apollo
|
tests/node_modules/graphql/utilities/concatAST.js
|
JavaScript
|
mit
| 861 |
myApp.controller('addTestsRobotCtrl', ['$scope', '$http', '$location', 'Flash', 'Session', '$cookies', 'AuthService', '$window', 'testParams', '$routeParams', function ($scope, $http, $location, Flash, Session, $cookies, AuthService, $window, testParams, $routeParams) {
$scope.isAuthenticated = AuthService.isAuthenticated();
$scope.testParams = testParams;
if($scope.isAuthenticated == false){
var message = 'Please Login first!';
var id = Flash.create('danger', message, 3500);
$location.path('/');
$window.location.reload();
};
$scope.array = [];
$scope.plan = {};
$scope.plan.userId = $cookies.getObject('loggedUser').userId;
$scope.plan.username = $cookies.getObject('loggedUser').username;
$scope.plan.id = $routeParams.id;
$scope.testCount = [{}];
$scope.addTest = function(){
$scope.testCount.push({})
}
$scope.insertTest = function(test){
$scope.planParams.push(this.test);
$scope.lock = true;
}
$scope.editToggle = function(){
$scope.lock = false;
$scope.planParams.splice(this.test, 1);
}
$scope.removeTest = function() {
$scope.testCount.splice($scope.testCount.length-1,1);
}
$scope.calc = false;
$scope.showCalc = function(){
$scope.calc = !$scope.calc;
};
$scope.addTestToPlan = function() {
$http.post('http://wigig-584/robot/addTests', {plan: $scope.plan, tests: $scope.array})
.then(function(response){
// if(response.data == 'success'){
// var message = 'Plan Created Succesfully!';
// var id = Flash.create('success', message, 3500);
// $location.path('/plans/'+$scope.plan.id);
// console.log(response.data)
// } else {
// var message = response.data;
// var id = Flash.create('danger', message, 3500);
// console.log(response.data);
// }
console.log(response.data);
})
};
}]);
|
M-Wittner/DVT
|
controllers/robot/addtests.controller.js
|
JavaScript
|
mit
| 1,791 |
import _ from 'lodash';
import { AttachmentSerializer } from '../../../models';
import { reportError } from '../../../support/exceptions';
export default class AttachmentsController {
app = null
constructor(app) {
this.app = app
}
create = async (ctx) => {
if (!ctx.state.user) {
ctx.status = 401;
ctx.body = { err: 'Not found' };
return
}
const fileHandlerPromises = _.map(ctx.request.body.files, async (file) => {
try {
const newAttachment = await ctx.state.user.newAttachment({ file });
await newAttachment.create();
const json = new AttachmentSerializer(newAttachment).promiseToJSON();
ctx.body = await json;
} catch (e) {
if (e.message && e.message.indexOf('Corrupt image') > -1) {
ctx.logger.warn(e.message);
const errorDetails = { message: 'Corrupt image' }
reportError(ctx)(errorDetails);
return;
}
if (e.message && e.message.indexOf('LCMS encoding') > -1) {
ctx.logger.warn(`GraphicsMagick should be configured with --with-lcms2 option`);
const errorDetails = { status: 500, message: 'Internal server error' }
reportError(ctx)(errorDetails);
return;
}
reportError(ctx)(e);
}
})
await Promise.all(fileHandlerPromises);
}
}
|
golozubov/freefeed-server
|
app/controllers/api/v1/AttachmentsController.js
|
JavaScript
|
mit
| 1,364 |
(function(test) {
if (typeof define == 'function' && define.amd)
define(['sfAngValid/constraints/True'], test);
else
test(sfAngValid.constraints.True);
}(function(True) {
describe('constraints/True', function() {
it('is a function', function() {
True.should.be.a('function');
});
describe('signature', function() {
it('accepts one object', function() {
function fails() { True(); }
fails.should.throw(Error);
});
it('must have a message property', function() {
function fails() { True({}); }
fails.should.throw(/message property/);
});
});
describe('return value', function() {
var backendConstraints = {
message: 'This value must be true.'
},
validator = True(backendConstraints);
it('is a function', function() {
validator.should.be.a('function');
});
it('returns an array', function() {
var returnValue = validator('');
returnValue.should.be.an.instanceof(Array);
});
it('returns the message for an input that is not true, 1, or "1"', function() {
var returnValue = validator('not true');
returnValue[0].should.equal(backendConstraints.message);
});
it('returns an empty array for true', function() {
var returnValue = validator(true);
returnValue.length.should.equal(0);
});
it('returns an empty array for 1', function() {
var returnValue = validator(1);
returnValue.length.should.equal(0);
});
it('returns an empty array for "1"', function() {
var returnValue = validator('1');
returnValue.length.should.equal(0);
});
});
});
}));
|
cameronprattedwards/sfAngValid
|
src/constraints/True_spec.js
|
JavaScript
|
mit
| 1,592 |
(function JVM_net_nexustools_website_BasicPageHandler($JVM, JVM){
$JVM.ClassLoader.defineClass("net/nexustools/website/BasicPageHandler", ["net/nexustools/website/PageHandler"], "java/lang/Object", [
{
"type": "method",
"name": "<init>",
"signature": "()V",
"sigparts": {
"return": JVM.Types.VOID,
"args": []
},
"implementation": [
{
"type": "label",
"name": "L598104600"
},
{
"type": "var",
"opcode": JVM.Opcodes.ALOAD,
"index": "0"
},
{
"type": "method",
"opcode": JVM.Opcodes.INVOKESPECIAL,
"owner": "java/lang/Object",
"name": "<init>",
"signature": {
"raw": "()V",
"return": JVM.Types.VOID,
"args": []
},
"interface": false
},
{
"type": "insn",
"opcode": JVM.Opcodes.RETURN
},
{
"type": "label",
"name": "L2120544240"
},
{
"type": "declare",
"name": "this",
"signature": "Lnet/nexustools/website/BasicPageHandler;",
"index": "0",
"start": "L598104600",
"end": "L2120544240"
},
{
"type": "end"
}
],
"access": [
JVM.Flags.PUBLIC
]
},
{
"type": "method",
"name": "onReady",
"signature": "(Lnet/nexustools/jvm/webdocument/dom/WebElement;)V",
"sigparts": {
"return": JVM.Types.VOID,
"args": [
"Lnet/nexustools/jvm/webdocument/dom/WebElement;"
]
},
"implementation": [
{
"type": "label",
"name": "L348436068"
},
{
"type": "insn",
"opcode": JVM.Opcodes.RETURN
},
{
"type": "label",
"name": "L2124573154"
},
{
"type": "declare",
"name": "this",
"signature": "Lnet/nexustools/website/BasicPageHandler;",
"index": "0",
"start": "L348436068",
"end": "L2124573154"
},
{
"type": "declare",
"name": "element",
"signature": "Lnet/nexustools/jvm/webdocument/dom/WebElement;",
"index": "1",
"start": "L348436068",
"end": "L2124573154"
},
{
"type": "end"
}
],
"access": [
JVM.Flags.PUBLIC
]
},
{
"type": "method",
"name": "onUnload",
"signature": "()V",
"sigparts": {
"return": JVM.Types.VOID,
"args": []
},
"implementation": [
{
"type": "label",
"name": "L1490400609"
},
{
"type": "insn",
"opcode": JVM.Opcodes.RETURN
},
{
"type": "label",
"name": "L913776855"
},
{
"type": "declare",
"name": "this",
"signature": "Lnet/nexustools/website/BasicPageHandler;",
"index": "0",
"start": "L1490400609",
"end": "L913776855"
},
{
"type": "end"
}
],
"access": [
JVM.Flags.PUBLIC
]
},
{
"type": "method",
"name": "onLoad",
"signature": "(Ljava/lang/String;[Ljava/lang/String;Ljava/util/Map;Lnet/nexustools/website/PageHandler$LoadCallback;)V",
"sigparts": {
"return": JVM.Types.VOID,
"args": [
"Ljava/lang/String;",
"[Ljava/lang/String;",
"Ljava/util/Map;",
"Lnet/nexustools/website/PageHandler$LoadCallback;"
]
},
"implementation": [
{
"type": "label",
"name": "L1192042288"
},
{
"type": "var",
"opcode": JVM.Opcodes.ALOAD,
"index": "4"
},
{
"type": "method",
"opcode": JVM.Opcodes.INVOKEINTERFACE,
"owner": "net/nexustools/website/PageHandler$LoadCallback",
"name": "ready",
"signature": {
"raw": "()V",
"return": JVM.Types.VOID,
"args": []
},
"interface": true
},
{
"type": "label",
"name": "L779791553"
},
{
"type": "insn",
"opcode": JVM.Opcodes.RETURN
},
{
"type": "label",
"name": "L2011417277"
},
{
"type": "declare",
"name": "this",
"signature": "Lnet/nexustools/website/BasicPageHandler;",
"index": "0",
"start": "L1192042288",
"end": "L2011417277"
},
{
"type": "declare",
"name": "path",
"signature": "Ljava/lang/String;",
"index": "1",
"start": "L1192042288",
"end": "L2011417277"
},
{
"type": "declare",
"name": "pathParams",
"signature": "[Ljava/lang/String;",
"index": "2",
"start": "L1192042288",
"end": "L2011417277"
},
{
"type": "declare",
"name": "params",
"signature": "Ljava/util/Map;",
"index": "3",
"start": "L1192042288",
"end": "L2011417277"
},
{
"type": "declare",
"name": "callback",
"signature": "Lnet/nexustools/website/PageHandler$LoadCallback;",
"index": "4",
"start": "L1192042288",
"end": "L2011417277"
},
{
"type": "end"
}
],
"access": [
JVM.Flags.PUBLIC
]
},
{
"type": "method",
"name": "onReady",
"signature": "(Ljava/lang/String;[Ljava/lang/String;Ljava/util/Map;Lnet/nexustools/jvm/webdocument/dom/WebElement;Ljava/lang/Runnable;)V",
"sigparts": {
"return": JVM.Types.VOID,
"args": [
"Ljava/lang/String;",
"[Ljava/lang/String;",
"Ljava/util/Map;",
"Lnet/nexustools/jvm/webdocument/dom/WebElement;",
"Ljava/lang/Runnable;"
]
},
"implementation": [
{
"type": "label",
"name": "L202603465"
},
{
"type": "var",
"opcode": JVM.Opcodes.ALOAD,
"index": "0"
},
{
"type": "var",
"opcode": JVM.Opcodes.ALOAD,
"index": "4"
},
{
"type": "method",
"opcode": JVM.Opcodes.INVOKEVIRTUAL,
"owner": "net/nexustools/website/BasicPageHandler",
"name": "onReady",
"signature": {
"raw": "(Lnet/nexustools/jvm/webdocument/dom/WebElement;)V",
"return": JVM.Types.VOID,
"args": [
"Lnet/nexustools/jvm/webdocument/dom/WebElement;"
]
},
"interface": false
},
{
"type": "label",
"name": "L1394855760"
},
{
"type": "insn",
"opcode": JVM.Opcodes.RETURN
},
{
"type": "label",
"name": "L1409267668"
},
{
"type": "declare",
"name": "this",
"signature": "Lnet/nexustools/website/BasicPageHandler;",
"index": "0",
"start": "L202603465",
"end": "L1409267668"
},
{
"type": "declare",
"name": "path",
"signature": "Ljava/lang/String;",
"index": "1",
"start": "L202603465",
"end": "L1409267668"
},
{
"type": "declare",
"name": "pathParams",
"signature": "[Ljava/lang/String;",
"index": "2",
"start": "L202603465",
"end": "L1409267668"
},
{
"type": "declare",
"name": "params",
"signature": "Ljava/util/Map;",
"index": "3",
"start": "L202603465",
"end": "L1409267668"
},
{
"type": "declare",
"name": "element",
"signature": "Lnet/nexustools/jvm/webdocument/dom/WebElement;",
"index": "4",
"start": "L202603465",
"end": "L1409267668"
},
{
"type": "declare",
"name": "complete",
"signature": "Ljava/lang/Runnable;",
"index": "5",
"start": "L202603465",
"end": "L1409267668"
},
{
"type": "end"
}
],
"access": [
JVM.Flags.FINAL,
JVM.Flags.PUBLIC
]
},
{
"type": "method",
"name": "onUnload",
"signature": "(Ljava/lang/Runnable;)V",
"sigparts": {
"return": JVM.Types.VOID,
"args": [
"Ljava/lang/Runnable;"
]
},
"implementation": [
{
"type": "label",
"name": "L964553313"
},
{
"type": "var",
"opcode": JVM.Opcodes.ALOAD,
"index": "0"
},
{
"type": "method",
"opcode": JVM.Opcodes.INVOKEVIRTUAL,
"owner": "net/nexustools/website/BasicPageHandler",
"name": "onUnload",
"signature": {
"raw": "()V",
"return": JVM.Types.VOID,
"args": []
},
"interface": false
},
{
"type": "label",
"name": "L2040964035"
},
{
"type": "var",
"opcode": JVM.Opcodes.ALOAD,
"index": "1"
},
{
"type": "method",
"opcode": JVM.Opcodes.INVOKEINTERFACE,
"owner": "java/lang/Runnable",
"name": "run",
"signature": {
"raw": "()V",
"return": JVM.Types.VOID,
"args": []
},
"interface": true
},
{
"type": "label",
"name": "L726242714"
},
{
"type": "insn",
"opcode": JVM.Opcodes.RETURN
},
{
"type": "label",
"name": "L1811728297"
},
{
"type": "declare",
"name": "this",
"signature": "Lnet/nexustools/website/BasicPageHandler;",
"index": "0",
"start": "L964553313",
"end": "L1811728297"
},
{
"type": "declare",
"name": "complete",
"signature": "Ljava/lang/Runnable;",
"index": "1",
"start": "L964553313",
"end": "L1811728297"
},
{
"type": "end"
}
],
"access": [
JVM.Flags.FINAL,
JVM.Flags.PUBLIC
]
},
{
"type": "references",
"value": [
"net/nexustools/website/PageHandler",
"java/lang/Object",
"net/nexustools/website/BasicPageHandler",
"net/nexustools/jvm/webdocument/dom/WebElement",
"java/lang/String",
"java/util/Map",
"net/nexustools/website/PageHandler$LoadCallback",
"java/lang/Runnable"
]
}
]);
})($currentJVM, JVM);
|
NexusTools/NexusToolsWebsite
|
src/static/jvm/net/nexustools/website/BasicPageHandler.js
|
JavaScript
|
mit
| 9,312 |
"use strict"
module.exports = () => {
// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
const shuffle = (array) => {
const currentIndex = array.length
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
let randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
// And swap it with the current element.
let temporaryValue = array[currentIndex]
array[currentIndex] = array[randomIndex]
array[randomIndex] = temporaryValue
}
return array
},
currentCard = 0
const deck = shuffle([
{
text: "EMERGENCY!!!! Go to the Monkey House because a monkey has hurt itself.",
action: "move",
location: 4
},
{
text: "A giraffe eats all your food so go and get more."
},
{
text: "A gust of wind blown the food out of your bucket. Go and get more."
},
{
text: "Somebody gives you a broom. Use it to clean an animals cage."
},
{
text: "You find food for any animal on the ground. Use it feed an animal."
},
{
text: "You find a mop left by another keeper. Use it to clean any animal."
},
{
text: "EMERGENCY!!! Go to the Reptile House because a lizard has escaped."
},
{
text: "You find a buggy. Go to your destination now."
},
{
text: "You trip up and your bucket of water goes flying. Go and get some more."
},
{
text: "The birds have made a mess. Clean them again."
},
{
text: "A snake is shedding, go to the Reptile House."
},
{
text: "A monkey needs medical care. Go to the Monkey House."
},
{
text: "You find a tractor heading to your destination. It breaks down. Miss a go."
}
])
return {
next() {
if (currentCard === deck.length) {
currentCard = 1
return deck[0]
} else {
return deck[currentCard++]
}
}
}
}
|
ultraflynn/zooaloo
|
lib/cards.js
|
JavaScript
|
mit
| 2,144 |
import Vue from "vue";
import { AgGridVue } from "@ag-grid-community/vue";
import { AllCommunityModules } from '@ag-grid-community/all-modules';
import "@ag-grid-community/all-modules/dist/styles/ag-grid.css";
import "@ag-grid-community/all-modules/dist/styles/ag-theme-alpine.css";
const VueExample = {
template: `
<div style="height: 100%; display: flex; flex-direction: column" class="ag-theme-alpine">
<ag-grid-vue style="flex: 1 1 auto;"
:gridOptions="topGridOptions"
@grid-ready="onGridReady"
@first-data-rendered="onFirstDataRendered"
:columnDefs="columnDefs"
:rowData="rowData"
:modules="modules"
></ag-grid-vue>
<ag-grid-vue style="height: 60px; flex: none;"
:gridOptions="bottomGridOptions"
:headerHeight="0"
:columnDefs="columnDefs"
:rowData="bottomData"
:modules="modules"
:rowStyle="rowStyle"
></ag-grid-vue>
</div>
`,
components: {
"ag-grid-vue": AgGridVue
},
data: function() {
return {
topGridOptions: null,
bottomGridOptions: null,
gridApi: null,
columnApi: null,
rowData: null,
bottomData: null,
columnDefs: null,
athleteVisible: true,
ageVisible: true,
countryVisible: true,
rowStyle: { fontWeight: 'bold' },
modules: AllCommunityModules
};
},
beforeMount() {
this.bottomData = [
{
athlete: 'Total',
age: '15 - 61',
country: 'Ireland',
year: '2020',
date: '26/11/1970',
sport: 'Synchronised Riding',
gold: 55,
silver: 65,
bronze: 12
}
];
this.topGridOptions = {
alignedGrids: [],
defaultColDef: {
editable: true,
sortable: true,
resizable: true,
filter: true,
flex: 1,
minWidth: 100
},
suppressHorizontalScroll: true
};
this.bottomGridOptions = {
alignedGrids: [],
defaultColDef: {
editable: true,
sortable: true,
resizable: true,
filter: true,
flex: 1,
minWidth: 100
}
};
this.topGridOptions.alignedGrids.push(this.bottomGridOptions);
this.bottomGridOptions.alignedGrids.push(this.topGridOptions);
this.columnDefs = [
{ field: 'athlete', width: 200, hide: !this.athleteVisible },
{ field: 'age', width: 150, hide: !this.ageVisible },
{ field: 'country', width: 150, hide: !this.countryVisible },
{ field: 'year', width: 120 },
{ field: 'date', width: 150 },
{ field: 'sport', width: 150 },
// in the total col, we have a value getter, which usually means we don't need to provide a field
// however the master/slave depends on the column id (which is derived from the field if provided) in
// order ot match up the columns
{
headerName: 'Total',
field: 'total',
valueGetter: 'data.gold + data.silver + data.bronze',
width: 200
},
{field: 'gold', width: 100},
{field: 'silver', width: 100},
{field: 'bronze', width: 100}
];
},
mounted() {
this.gridApi = this.topGridOptions.api;
this.gridColumnApi = this.topGridOptions.columnApi;
},
methods: {
onGridReady(params) {
const httpRequest = new XMLHttpRequest();
const updateData = data => {
this.rowData = data;
};
httpRequest.open(
"GET",
'https://www.ag-grid.com/example-assets/olympic-winners.json'
);
httpRequest.send();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
updateData(JSON.parse(httpRequest.responseText));
}
};
},
onFirstDataRendered: function() {
this.gridColumnApi.autoSizeAllColumns();
}
},
};
new Vue({
el: "#app",
components: {
"my-component": VueExample
}
});
|
ceolter/ag-grid
|
grid-packages/ag-grid-docs/documentation/doc-pages/aligned-grids/examples/aligned-floating-footer/vue/main.js
|
JavaScript
|
mit
| 4,828 |
define({
OK : 'OK',
CANCEL : 'Annuler',
CONFIRM : 'OK'
});
|
ligoj/ligoj
|
app-ui/src/main/webapp/lib/bootbox/nls/fr/bootbox-messages.js
|
JavaScript
|
mit
| 76 |
'use strict';
var React = require('react');
var FileInput = module.exports.FileInput = React.createClass({
getInitialState: function() {
return {
value: this.props.value || {},
};
},
componentWillReceiveProps: function(nextProps) {
this.setState({value: nextProps.value});
},
render: function() {
var mimetype = this.state.value.type;
var preview = (mimetype && mimetype.indexOf('image/') === 0) ? <img src={this.state.value.href} width="128" /> : '';
var filename = this.state.value.download;
return (
<div className="dropzone" onDragOver={this.onDragOver} onDrop={this.onDrop}>
<div className="drop">
{filename ? <div>
<a href={this.state.value.href} target="_blank">{filename}</a>
</div> : ''}
<div>{preview}</div>
<br />Drop a {filename ? 'replacement' : ''} file here.
Or <input ref="input" type="file" onChange={this.onChange} />
<br /><br />
</div>
</div>
);
},
onDragOver: function(e) {
e.dataTransfer.dropEffect = 'copy';
e.preventDefault(); // indicate we are going to handle the drop
},
onDrop: function(e) {
var file = e.dataTransfer.files[0];
this.onChange(null, file);
e.preventDefault();
},
onChange: function(e, file) {
if (file === undefined) {
var input = this.refs.input.getDOMNode();
file = input.files[0];
}
var reader = new FileReader();
reader.onloadend = function() {
var value = {
download: file.name,
type: file.type,
href: reader.result
};
this.props.onChange(value);
}.bind(this);
if (file) {
reader.readAsDataURL(file);
}
}
});
module.exports = FileInput;
|
philiptzou/clincoded
|
src/clincoded/static/components/inputs/file.js
|
JavaScript
|
mit
| 2,041 |
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
class ModalHeader extends PureComponent {
render() {
const { hideCloseButton, className, children } = this.props;
let closeButton = null;
if (!hideCloseButton) {
closeButton = (
<button type="button" className="btn btn--compact modal__close-btn" data-close-modal="true">
<i className="fa fa-times" />
</button>
);
}
return (
<div className={classnames('modal__header theme--dialog__header', className)}>
<div className="modal__header__children">{children}</div>
{closeButton}
</div>
);
}
}
ModalHeader.propTypes = {
// Required
children: PropTypes.node.isRequired,
// Optional
hideCloseButton: PropTypes.bool,
className: PropTypes.string
};
export default ModalHeader;
|
Atvaark/insomnia
|
packages/insomnia-app/app/ui/components/base/modal-header.js
|
JavaScript
|
mit
| 898 |
#!/usr/bin/env node
'use strict';
var argv = require('yargs')
.usage('ddm [--port 3000] [--druidsPort 3001]')
// option: port
.string('port')
.alias('p', 'port')
.describe('port', 'The port druid-dm will run on, defaults to 3061')
// flag: help
.help('h')
// flag: version
.version()
//defaults
.default('p', 3221)
.argv;
console.log(argv);
require('../lib/druid-dm').serve(argv);
|
kevin-smets/druid-dm
|
bin/ddm.js
|
JavaScript
|
mit
| 437 |
import fs from 'fs';
import { parse } from '..';
let sdf = fs.readFileSync(`${__dirname}/test.sdf`, 'utf-8');
describe('SDF Parser options and undefined', () => {
let result = parse(sdf, {
exclude: ['Number of H-Donors'],
include: ['Number of H-Donors', 'CLogP', 'Code'],
modifiers: {
CLogP: () => {
return undefined;
},
},
filter: (entry) => {
return entry.CLogP && entry.CLogP.low > 4;
},
});
it('Check molecules', () => {
expect(result.molecules).toHaveLength(0);
});
});
|
cheminfo/sdf-parser
|
src/__tests__/checkUndefined.test.js
|
JavaScript
|
mit
| 541 |
Ext.define("Com.GatotKaca.ERP.module.HumanResources.store.OverTimeByDate",{extend:"Com.GatotKaca.ERP.store.Base",model:"Com.GatotKaca.ERP.module.HumanResources.model.OverTimeDetail",proxy:{type:"ajax",api:{read:BASE_URL+"human_resources/overtime/getbydate"},actionMethods:{read:"POST"},reader:{type:"json",root:"data",successProperty:"success",totalProperty:"total"},writer:{type:"json",writeAllFields:true,root:"data",encode:true}}});
|
AdenKejawen/erp
|
web/assets/app/module/HumanResources/store/OverTimeByDate.js
|
JavaScript
|
mit
| 435 |
module.exports = exports = (function() {
var config = requireApp('/config/cache');
var Memcached = require('memcached');
var client = new Memcached(config.host + ':' + config.port);
var Cache = {
set: function(key, value, callback) {
client.set(key, value, config.lifetime, function(err, result){
if (callback) callback(result);
});
},
get: function(key, callback) {
client.get(key, function(err, result){
if (callback) callback(result);
});
},
flush: function() {
client.flush(function(err, result){
if(err) console.error(err);
});
}
};
return Cache;
})();
|
badsyntax/xen
|
xen/cache/drivers/memcached.js
|
JavaScript
|
mit
| 656 |
var debounce = require('debounce')
, lsb = require('./')
, encode = lsb.encode
, decode = lsb.decode
var input = document.getElementById('input').getContext('2d')
, output = document.getElementById('output').getContext('2d')
, highlighted = document.getElementById('highlighted').getContext('2d')
, enlarged = document.getElementById('enlarged').getContext('2d')
, textarea = document.getElementById('text')
;[input, output, highlighted, enlarged].forEach(function(c) {
c.canvas.width = 256
c.canvas.height = 256
})
var nyan = new Image
nyan.onload = function() {
;[input, output].forEach(function(c) {
c.drawImage(nyan, 0, 0, c.canvas.width, c.canvas.height)
})
updateText()
}
nyan.src = 'img/nyan.png'
textarea.onkeyup =
textarea.onchange = updateText
function updateText() {
var stegotext = textarea.value + ''
, imageData = input.getImageData(0, 0, input.canvas.width, input.canvas.height)
// Encode image data - ignoring the alpha channel
// as it would interfere with the RGB channels
function rgb(n) {
return n + (n/3)|0
}
encode(imageData.data, stegotext, rgb)
output.putImageData(imageData, 0, 0)
// Highlight LSBs
for (var i = rgb(4), l = imageData.data.length; i < l; i += 1) {
imageData.data[i] = imageData.data[i] & 1 ? 255 : 0
}
highlighted.putImageData(imageData, 0, 0)
// Enlarge the first 100 bits of the image,
// with R/G/B on seperate pixels
for (var x = 0; x < 64; x += 1) {
for (var y = 0; y < 64; y += 1) {
var val = imageData.data[rgb(x+y*64)]
enlarged.fillStyle = 'rgb('
+ val + ','
+ val + ','
+ val + ')'
enlarged.fillRect(x * 8, y * 8, 8, 8)
}
}
}
updateText = debounce(updateText, 50, true)
|
jlord/lsb
|
example.js
|
JavaScript
|
mit
| 1,752 |
/* A entry point for the browser bundle version. This gets compiled by:
browserify --debug ./ccxt.browser.js > ./build/ccxt.browser.js
*/
window.ccxt = require ('./ccxt')
|
tritoanst/ccxt
|
ccxt.browser.js
|
JavaScript
|
mit
| 190 |
(function () {
angular.module('bldWelcomeController', [])
.controller('WelcomeCtrl', WelcomeCtrl);
function WelcomeCtrl() {
var home = this;
}
})();
|
levilindsey/benlindseydesign.com
|
src/routes/welcome/welcome-controller.js
|
JavaScript
|
mit
| 165 |
(function()
{
'use strict';
// Register the Player component and mark the Image
// and Velocity components as required.
// The Image and Velocity components both include
// Pos2D themselves
TANK.registerComponent('Player')
.includes(['Image', 'Velocity'])
.construct(function()
{
// Set some default values for the Player controller
// Define things in the constructor that you want to be able to
// override before initialize() is called
this.speed = 100;
this.gravity = 400;
this.fuelDrain = 4;
this.fuelGain = 2;
this.fuel = 10;
this.jumpThrust = 500;
this.up = false;
this.gunAngle = -Math.PI / 6;
})
.initialize(function()
{
// Store sibling components for use later on
// This is a bad idea if the components might be removed at runtime.
// But I don't plan on ever removing Pos2D or Velocity from this object.
var t = this._entity.Pos2D;
var v = this._entity.Velocity;
// Load the image for the player
this._entity.Image.image.src = 'space-tank.png';
this._entity.Image.scale = 5;
this._entity.Image.pivotPoint[1] = -8;
// Set initial horizontal speed
v.x = this.speed;
// Define a function for shooting
this.shoot = function()
{
// Create a new entity using the Bullet component and position it
// accordingly
var e = TANK.createEntity('Bullet');
e.Pos2D.x = t.x + Math.cos(this.gunAngle + t.rotation) * 50;
e.Pos2D.y = t.y - 40 + Math.sin(this.gunAngle + t.rotation) * 50;
e.Velocity.x = Math.cos(this.gunAngle + t.rotation) * 700;
e.Velocity.y = Math.sin(this.gunAngle + t.rotation) * 700;
TANK.main.addChild(e);
};
// Implement the update function to get access to the update loop
// dt is passed in as seconds
this.update = function(dt)
{
// Update fuel
this.fuel += this.fuelGain * dt;
if (this.fuel > 10)
this.fuel = 10;
// Get the ground component from the Level entity
var ground = TANK.main.getChild('Level').Ground;
// Gravity
var groundHeight = ground.getHeight(t.x);
if (t.y < groundHeight)
{
v.y += this.gravity * dt;
}
else
{
v.y = 0;
t.y = groundHeight;
t.rotation = ground.getAngle(t.x);
}
// Handle thrust
if (this.up && this.fuel > 0)
{
this.fuel -= this.fuelDrain * dt;
v.y -= this.jumpThrust * dt;
}
// Move camera
TANK.main.Renderer2D.camera.x = t.x + 400;
};
// Listen for the keydown event on the main engine entity
// since that is the one with the Input component on it
this.listenTo(TANK.main, 'keydown', function(e)
{
if (e.keyCode === TANK.Key.W)
this.up = true;
if (e.keyCode === TANK.Key.SPACE)
this.shoot();
});
this.listenTo(TANK.main, 'keyup', function(e)
{
if (e.keyCode === TANK.Key.W)
this.up = false;
});
});
})();
|
phosphoer/tankjs
|
samples/space-tank/Player.js
|
JavaScript
|
mit
| 3,013 |
/* eslint no-console: ["off"] */
const chalk = require('chalk');
const logPrefix = '[WebpackSlowPlugin]: ';
function SlowWebpackPlugin(options) {
const delay = parseInt(options.delay, 10);
const cleanOptions = Object.assign(
{},
options,
{ delay: !isNaN(delay) ? delay : 1000 }
);
this.options = cleanOptions;
}
SlowWebpackPlugin.prototype.apply = function apply(compiler) {
const delay = this.options.delay;
compiler.plugin('done', () => {
const beginTime = Date.now();
let curTime = beginTime;
let secondsElapsed = 0;
console.log('');
console.log(chalk.yellow(`${logPrefix}Begin`));
while (curTime - beginTime < delay) {
curTime = Date.now();
if (Math.floor((curTime - beginTime) / 1000) > secondsElapsed) {
secondsElapsed += 1;
console.log(chalk.yellow(`${logPrefix + secondsElapsed}/${Math.ceil(delay / 1000)}`));
}
}
console.log(chalk.yellow(`${logPrefix}End`));
console.log('');
});
};
module.exports = SlowWebpackPlugin;
|
raquo/minimal-hapi-react-webpack
|
src/tools/slow-webpack-plugin.js
|
JavaScript
|
mit
| 1,034 |
/*
* Rand Movie App 0.0.1
* github.com/weslleyaraujo
* Note: Model for one movie
*/
RandMovieApp.Models.Movie = Backbone.Model.extend({
defaults: {
'plot_simple' : 'No description :(',
'is_small': ''
},
initialize: function () {
this.titleLenght();
randMovie.setTitle(this);
},
titleLenght: function () {
var title = this.get('title');
if (title.length >= 40) {
this.set('is_small', 'is-small');
}
}
})
|
weslleyaraujo/randmovie
|
public/js/app/models/RandMovieApp.Models.Movie.js
|
JavaScript
|
mit
| 435 |
Ext.onReady( function() {
Ext.application({
requires: [
'GeoPal.view.mapsemployees.Init',
'GeoPal.controller.MapsEmployees'
],
name: 'GeoPal',
appFolder: 'assets/js/GeoPal/app',
autoCreateViewport: true,
controllers: [
'MapsEmployees'
]
});
});
setTimeout(function(){
delete Ext.tip.Tip.prototype.minWidth;
}, 2000);
|
geopal-solutions/geopal-map-tracker
|
assets/js/GeoPal/app.js
|
JavaScript
|
mit
| 427 |
import wu from '../es6/wu';
import { assert } from 'chai';
describe("wu.some", () => {
it("should return true if any item matches the predicate", () => {
assert.ok(wu.some(x => x % 2 === 0, [1,2,3]));
});
it("should return false if no items match the predicate", () => {
assert.ok(!wu.some(x => x % 5 === 0, [1,2,3]));
});
});
|
jonrimmer/wu-babel
|
test/test-some.js
|
JavaScript
|
mit
| 345 |
const build = require('./build')
const dev = require('./dev')
const init = require('./init')
module.exports = {
build,
dev,
init,
}
|
farism/elm-factory
|
src/cmds/index.js
|
JavaScript
|
mit
| 139 |
var should = require('should'),
expect = require('expect.js'),
fast = require('../lib')();
describe('fast.bind()', function () {
var input = function (a, b, c) {
return a + b + c + this.seed;
};
var object = {
seed: 100
};
it('should bind to a context', function () {
var bound = fast.bind(input, object);
bound(1,2,3).should.equal(106);
});
it('should partially apply a function', function () {
var bound = fast.bind(input, object, 1, 2);
bound(3).should.equal(106);
});
});
describe('fast.partial()', function () {
var input = function (a, b, c) {
return a + b + c + this.seed;
};
var object = {
seed: 100
};
it('should partially apply a function', function () {
object.foo = fast.partial(input, 1, 2);
object.foo(3).should.equal(106);
})
});
describe('fast.partialConstructor()', function () {
var Constructor = function (baz, greeting) {
this.bar = 10;
this.baz = baz;
this.greeting = greeting;
};
Constructor.prototype.foo = function () {
return this.bar + this.baz;
};
var Partial = fast.partialConstructor(Constructor, 32),
instance;
beforeEach(function () {
instance = new Partial("hello world");
});
it('should be an instanceof the original constructor', function () {
instance.should.be.an.instanceOf(Constructor);
});
it('should apply the bound arguments', function () {
instance.baz.should.equal(32);
});
it('should apply the supplied arguments', function () {
instance.greeting.should.equal("hello world");
});
it('should supply methods from the prototype', function () {
instance.foo().should.equal(42);
});
it('should work without the new keyword', function () {
instance = Partial('hello world');
instance.should.be.an.instanceOf(Constructor);
instance.foo().should.equal(42);
instance.greeting.should.equal('hello world');
});
});
describe('fast.clone()', function () {
it('should return primitives directly', function () {
fast.clone(0).should.equal(0);
fast.clone("hello world").should.equal("hello world");
});
it('should clone arrays', function () {
fast.clone([1,2,3]).should.eql([1,2,3]);
});
it('should clone objects', function () {
fast.clone({a: 1, b: 2, c: 3}).should.eql({a: 1, b: 2, c: 3});
});
});
describe('fast.cloneArray()', function () {
var input = [1,2,3,4,5];
it('should clone an array', function () {
fast.cloneArray(input).should.eql(input);
});
it('should clone an arguments object', function () {
// don't actually do this, it leaks the arguments object
(function () { return fast.cloneArray(arguments); }).apply(this, input).should.eql(input);
});
});
describe('fast.cloneObject()', function () {
var input = {
a: 1,
b: 2,
c: 3
};
it('should clone an object', function () {
fast.cloneObject(input).should.eql(input);
});
});
describe('fast.concat()', function () {
var input = [1, 2, 3];
it('should concatenate an array of items', function () {
fast.concat(input, [4, 5, 6]).should.eql([1,2,3,4,5,6]);
});
it('should concatenate a list of items', function () {
fast.concat(input, 4, 5, 6).should.eql([1,2,3,4,5,6]);
});
it('should concatenate a mixed array / list of items', function () {
fast.concat(input, [4, 5], 6).should.eql([1,2,3,4,5,6]);
});
});
describe('fast.map()', function () {
var input = [1,2,3,4,5];
it('should map over a list of items', function () {
var result = fast.map(input, function (item) {
return item * item;
});
result.should.eql([1, 4, 9, 16, 25]);
});
it('should take context', function () {
fast.map([1], function () {
this.should.equal(fast);
}, fast);
});
});
describe('fast.filter()', function () {
var input = [1,2,3,4,5];
it('should filter a list of items', function () {
var result = fast.filter(input, function (item) {
return item % 2;
});
result.should.eql([1, 3, 5]);
});
it('should take context', function () {
fast.map([1], function () {
this.should.equal(fast);
}, fast);
});
});
describe('fast.reduce()', function () {
var input = [1,2,3,4,5];
it('should reduce a list of items', function () {
var result = fast.reduce(input, function (last, item) {
return last + item;
}, 0);
result.should.equal(15);
});
it('should take context', function () {
fast.reduce([1], function () {
this.should.equal(fast);
}, {}, fast);
});
it('should use input[0] if initialValue isn\'t provided', function() {
var result = fast.reduce(input, function (last, item) {
return last + item;
});
result.should.equal(15);
});
});
describe('fast.reduceRight()', function () {
var input = ["a", "b", "c"];
it('should reduce a list of items', function () {
var result = fast.reduceRight(input, function (last, item) {
return last + item;
}, "z");
result.should.equal("zcba");
});
it('should take context', function () {
fast.reduceRight([1], function () {
this.should.equal(fast);
}, {}, fast);
});
it('should use input[input.length - 1] if initialValue isn\'t provided', function() {
var result = fast.reduceRight(input, function (last, item) {
return last + item;
});
result.should.equal("cba");
});
});
describe('fast.forEach()', function () {
var input = [1,2,3,4,5];
it('should iterate over a list of items', function () {
var result = 0;
fast.forEach(input, function (item) {
result += item;
});
result.should.equal(15);
});
it('should take context', function () {
fast.forEach([1], function () {
this.should.equal(fast);
}, fast);
});
});
describe('fast.some()', function () {
var input = [1,2,3,4,5];
it('should return true if the check passes', function () {
var result = fast.some(input, function (item) {
return item === 3;
});
result.should.be.true;
});
it('should return false if the check fails', function () {
var result = fast.some(input, function (item) {
return item === 30000;
});
result.should.be.false;
});
it('should take context', function () {
fast.some([1], function () {
this.should.equal(fast);
}, fast);
});
});
describe('fast.indexOf()', function () {
var input = [1,2,3,4,5];
it('should return the index of the first item', function () {
fast.indexOf(input, 1).should.equal(0);
});
it('should return the index of the last item', function () {
fast.indexOf(input, 5).should.equal(4);
});
it('should return -1 if the item does not exist in the array', function () {
fast.indexOf(input, 1000).should.equal(-1);
});
var arr = [1,2,3];
arr[-2] = 4; // Throw a wrench in the gears by assigning a non-valid array index as object property.
it('finds 1', function() {
fast.indexOf(arr, 1).should.equal(0);
});
it('finds 1 and is result strictly it', function() {
fast.indexOf(arr, 1).should.equal(0);
});
it('does not find 4', function() {
fast.indexOf(arr, 4).should.equal(-1);
});
it('Uses strict equality', function() {
fast.indexOf(arr, '1').should.equal(-1);
});
it('from index 1', function() {
fast.indexOf(arr, 2, 1).should.equal(1);
});
it('from index 2', function() {
fast.indexOf(arr, 2, 2).should.equal(-1);
});
it('from index 3', function() {
fast.indexOf(arr, 2, 3).should.equal(-1);
});
it('from index 4', function() {
fast.indexOf(arr, 2, 4).should.equal(-1);
});
it('from index -1', function() {
fast.indexOf(arr, 3, -1).should.equal(2);
});
it('from index -2', function() {
fast.indexOf(arr, 3, -2).should.equal(2);
});
it('from index -3', function() {
fast.indexOf(arr, 3, -3).should.equal(2);
});
it('from index -4', function() {
fast.indexOf(arr, 3, -4).should.equal(2);
});
});
describe('fast.lastIndexOf()', function () {
var input = [1,2,3,4,5,1];
it('should return the last index of the first item', function () {
fast.lastIndexOf(input, 1).should.equal(5);
});
it('should return the index of the last item', function () {
fast.lastIndexOf(input, 5).should.equal(4);
});
it('should return -1 if the item does not exist in the array', function () {
fast.lastIndexOf(input, 1000).should.equal(-1);
});
var arr = ['a', 1, 'a'];
arr[-2] = 'a'; // Throw a wrench in the gears by assigning a non-valid array index as object property.
it('Array#lastIndexOf | finds a', function () {
fast.lastIndexOf(arr, 'a').should.equal(2);
});
it('Array#lastIndexOf | does not find c', function () {
fast.lastIndexOf(arr, 'c').should.equal(-1);
});
it( 'Array#lastIndexOf | Uses strict equality', function () {
fast.lastIndexOf(arr, '1').should.equal(-1);
});
it( 'Array#lastIndexOf | from index 1', function () {
fast.lastIndexOf(arr, 'a', 1).should.equal(0);
});
it( 'Array#lastIndexOf | from index 2', function () {
fast.lastIndexOf(arr, 'a', 2).should.equal(2);
});
it( 'Array#lastIndexOf | from index 3', function () {
fast.lastIndexOf(arr, 'a', 3).should.equal(2);
});
it( 'Array#lastIndexOf | from index 4', function () {
fast.lastIndexOf(arr, 'a', 4).should.equal(2);
});
it( 'Array#lastIndexOf | from index 0', function () {
fast.lastIndexOf(arr, 'a', 0).should.equal(0);
});
it('Array#lastIndexOf | from index -1', function () {
fast.lastIndexOf(arr, 'a', -1).should.equal(2);
});
it('Array#lastIndexOf | from index -2', function () {
fast.lastIndexOf(arr, 'a', -2).should.equal(0);
});
it('Array#lastIndexOf | from index -3', function () {
fast.lastIndexOf(arr, 'a', -3).should.equal(0);
});
it('Array#lastIndexOf | from index -4', function () {
fast.lastIndexOf(arr, 'a', -4).should.equal(-1);
});
});
describe('fast.try()', function () {
it('should return the value', function () {
var result = fast.try(function () {
return 123;
});
result.should.equal(123);
});
it('should return the error, if thrown', function () {
var result = fast.try(function () {
throw new Error('foo');
});
result.should.be.an.instanceOf(Error);
});
it('should return the error, if thrown, even if it\'s a string error', function () {
var result = fast.try(function () {
throw "Please don't do this, use an Error object";
});
result.should.be.an.instanceOf(Error);
});
});
describe('fast.apply()', function () {
var fn = function (a, b, c, d, e, f, g, h, i, j, k) {
return {
a: a,
b: b,
c: c,
d: d,
e: e,
f: f,
g: g,
h: h,
i: i,
j: j,
this: this
};
};
describe('noContext', function () {
it ('should apply 0 arguments', function () {
var result = fast.apply(fn, undefined, []);
expect(result.a).to.equal(undefined);
});
it ('should apply 1 argument', function () {
var result = fast.apply(fn, undefined, [1]);
expect(result.a).to.equal(1);
});
it ('should apply 2 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
});
it ('should apply 3 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
});
it ('should apply 4 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
});
it ('should apply 5 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4, 5]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
});
it ('should apply 6 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4, 5, 6]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
});
it ('should apply 7 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4, 5, 6, 7]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
});
it ('should apply 8 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4, 5, 6, 7, 8]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
expect(result.h).to.equal(8);
});
it ('should apply 9 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
expect(result.h).to.equal(8);
expect(result.i).to.equal(9);
});
it ('should apply 10 arguments', function () {
var result = fast.apply(fn, undefined, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
expect(result.h).to.equal(8);
expect(result.i).to.equal(9);
expect(result.j).to.equal(10);
});
});
describe('withContext', function () {
var obj = {};
it ('should apply 0 arguments', function () {
var result = fast.apply(fn, obj, []);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(undefined);
});
it ('should apply 1 argument', function () {
var result = fast.apply(fn, obj, [1]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
});
it ('should apply 2 arguments', function () {
var result = fast.apply(fn, obj, [1, 2]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
});
it ('should apply 3 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
});
it ('should apply 4 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
});
it ('should apply 5 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4, 5]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
});
it ('should apply 6 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4, 5, 6]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
});
it ('should apply 7 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4, 5, 6, 7]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
});
it ('should apply 8 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4, 5, 6, 7, 8]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
expect(result.h).to.equal(8);
});
it ('should apply 9 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
expect(result.h).to.equal(8);
expect(result.i).to.equal(9);
});
it ('should apply 10 arguments', function () {
var result = fast.apply(fn, obj, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
expect(result.this).to.equal(obj);
expect(result.a).to.equal(1);
expect(result.b).to.equal(2);
expect(result.c).to.equal(3);
expect(result.d).to.equal(4);
expect(result.e).to.equal(5);
expect(result.f).to.equal(6);
expect(result.g).to.equal(7);
expect(result.h).to.equal(8);
expect(result.i).to.equal(9);
expect(result.j).to.equal(10);
});
});
});
describe('Fast', function () {
var input = fast([1,2,3,4,5,6]);
describe('constructor', function () {
it('should return a Fast instance', function () {
input.should.be.an.instanceOf(fast);
});
it('should wrap the value', function () {
input.value.should.eql([1,2,3,4,5,6]);
});
it('should assign an empty array if none given', function () {
fast().length.should.equal(0);
fast().value.should.eql([]);
});
});
describe('length', function () {
it('should give the correct length', function () {
input.length.should.equal(6);
});
})
it('should map over the list', function () {
var result = input.map(function (item) {
return item * 2;
});
result.should.be.an.instanceOf(fast);
result.length.should.equal(6);
result.value.should.eql([2,4,6,8,10,12]);
});
it('should filter the list', function () {
var result = input.filter(function (item) {
return item % 2;
});
result.should.be.an.instanceOf(fast);
result.value.should.eql([1,3,5]);
});
it('should reduce over the list', function () {
var result = input.reduce(function (last, item) {
return last + item
});
result.should.equal(21);
});
it('should iterate over the list', function () {
var result = 0;
input.forEach(function (item) {
result += item;
});
result.should.equal(21);
});
it('should return true for ', function () {
var result = input.reduce(function (last, item) {
return last + item
});
result.should.equal(21);
});
describe('integration', function () {
var result;
beforeEach(function () {
result = input
.map(function (item) {
return item * 2;
})
.reverse()
.filter(function (item) {
return item % 3 === 0;
})
.map(function (item) {
return item / 2;
})
.concat(1, [2, 3]);
});
it('should perform functions in a chain', function () {
result.should.be.an.instanceOf(fast);
});
it('reduce to a final value', function () {
result.reduce(function (a, b) { return a + b; }).should.equal(15);
});
});
});
|
nickb1080/fast-poser
|
test/test.js
|
JavaScript
|
mit
| 20,153 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$( document ).ready(function() {
if (localStorage.deleteMapaOutside){
$("#dialog").css("visibility","visible");
localStorage.removeItem("deleteMapaOutside");
}
});
function borrarMapaMentalOutside(idMapa,idEstudiante){
$.ajax({
type: 'post',
url: Routing.generate('borrar_mapamental_outside', { idMapa: idMapa }),
success: function(data) {
window.location.href = Routing.generate('mapas_mentales',{'idEstudiante':idEstudiante});
localStorage.deleteMapaOutside = "true";
},
error: function (data2){
console.log(data2);
}
});
}
|
gabrielescobar/TesisEvaluaUcab
|
src/evaluaUcab/EstudianteBundle/Resources/public/js/mapaMentalFunctions.js
|
JavaScript
|
mit
| 831 |
'use strict';
var fetch = require('isomorphic-fetch');
module.exports = function (q) {
return fetch('http://kat.ph/json.php?q=' + q.replace(' ', '%20')).then(function (a) {
return a.json();
}).then(function (a) {
return a.list.map(function (item) {
return {
title: item.title,
magnet: 'magnet:?xt=urn:btih:' + item.hash
};
});
});
};
|
oeb25/kat
|
lib/index.js
|
JavaScript
|
mit
| 381 |
const path = require(`path`)
const locales = require(`./config/i18n`)
const {
localizedSlug,
findKey,
removeTrailingSlash,
} = require(`./src/utils/gatsby-node-helpers`)
exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions
// First delete the incoming page that was automatically created by Gatsby
// So everything in src/pages/
deletePage(page)
// Grab the keys ('en' & 'de') of locales and map over them
Object.keys(locales).map(lang => {
// Use the values defined in "locales" to construct the path
const localizedPath = locales[lang].default
? page.path
: `${locales[lang].path}${page.path}`
return createPage({
// Pass on everything from the original page
...page,
// Since page.path returns with a trailing slash (e.g. "/de/")
// We want to remove that
path: removeTrailingSlash(localizedPath),
// Pass in the locale as context to every page
// This context also gets passed to the src/components/layout file
// This should ensure that the locale is available on every page
context: {
...page.context,
locale: lang,
dateFormat: locales[lang].dateFormat,
},
})
})
}
// As you don't want to manually add the correct language to the frontmatter of each file
// a new node is created automatically with the filename
// It's necessary to do that -- otherwise you couldn't filter by language
exports.onCreateNode = ({ node, actions }) => {
const { createNodeField } = actions
// Check for "Mdx" type so that other files (e.g. images) are exluded
if (node.internal.type === `Mdx`) {
// Use path.basename
// https://nodejs.org/api/path.html#path_path_basename_path_ext
const name = path.basename(node.fileAbsolutePath, `.mdx`)
// Check if post.name is "index" -- because that's the file for default language
// (In this case "en")
const isDefault = name === `index`
// Find the key that has "default: true" set (in this case it returns "en")
const defaultKey = findKey(locales, o => o.default === true)
// Files are defined with "name-with-dashes.lang.mdx"
// name returns "name-with-dashes.lang"
// So grab the lang from that string
// If it's the default language, pass the locale for that
const lang = isDefault ? defaultKey : name.split(`.`)[1]
createNodeField({ node, name: `locale`, value: lang })
createNodeField({ node, name: `isDefault`, value: isDefault })
}
}
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const postTemplate = require.resolve(`./src/templates/post.js`)
const result = await graphql(`
{
blog: allFile(filter: { sourceInstanceName: { eq: "blog" } }) {
edges {
node {
relativeDirectory
childMdx {
fields {
locale
isDefault
}
frontmatter {
title
}
}
}
}
}
}
`)
if (result.errors) {
console.error(result.errors)
return
}
const postList = result.data.blog.edges
postList.forEach(({ node: post }) => {
// All files for a blogpost are stored in a folder
// relativeDirectory is the name of the folder
const slug = post.relativeDirectory
const title = post.childMdx.frontmatter.title
// Use the fields created in exports.onCreateNode
const locale = post.childMdx.fields.locale
const isDefault = post.childMdx.fields.isDefault
createPage({
path: localizedSlug({ isDefault, locale, slug }),
component: postTemplate,
context: {
// Pass both the "title" and "locale" to find a unique file
// Only the title would not have been sufficient as articles could have the same title
// in different languages, e.g. because an english phrase is also common in german
locale,
title,
},
})
})
}
|
gatsbyjs/gatsby
|
examples/using-i18n/gatsby-node.js
|
JavaScript
|
mit
| 4,018 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.