diff --git a/Gemfile b/Gemfile
index f5358f47..51ddc1db 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,5 +1,5 @@
source 'https://rubygems.org'
-ruby '1.9.3'
+#ruby '1.9.3'
gem 'rails', '3.2.17'
@@ -35,7 +35,7 @@ group :assets do
end
group :production do #this is used on heroku
- gem 'rmagick'
+ #gem 'rmagick'
end
gem 'jquery-rails', '2.1.2'
diff --git a/app/assets/javascripts/Jit/graphsettings-event-handlers.js b/app/assets/javascripts/Jit/graphsettings-event-handlers.js
index 6b9c25fb..ba18d621 100644
--- a/app/assets/javascripts/Jit/graphsettings-event-handlers.js
+++ b/app/assets/javascripts/Jit/graphsettings-event-handlers.js
@@ -585,47 +585,4 @@ function touchPanZoomHandler(eventInfo, e) {
lastDist = dist;
}
-}
-
-function updateSelectedPermissions(permission) {
-
-
- if ($('.notice.metamaps').length == 0) {
- $('body').prepend('
');
- }
- $('.notice.metamaps').hide().html('Working...').fadeIn('fast');
-
- // variables to keep track of how many nodes and synapses you had the ability to change the permission of
- var nCount = 0,
- sCount = 0;
-
- // change the permission of the selected synapses, if logged in user is the original creator
- var l = MetamapsModel.selectedEdges.length;
- for (var i = l - 1; i >= 0; i -= 1) {
- var edge = MetamapsModel.selectedEdges[i];
-
- if (edge.getData('userid') == userid) {
- updateSynapsePermission(edge, permission);
- sCount++;
- }
- }
-
- // change the permission of the selected topics, if logged in user is the original creator
- var l = MetamapsModel.selectedNodes.length;
- for (var i = l - 1; i >= 0; i -= 1) {
- var node = MetamapsModel.selectedNodes[i];
-
- if (node.getData('userid') == userid) {
- updateTopicPermission(node, permission);
- nCount++;
- }
- }
-
- var nString = nCount == 1 ? (nCount.toString() + ' topic and ') : (nCount.toString() + ' topics and ');
- var sString = sCount == 1 ? (sCount.toString() + ' synapse') : (sCount.toString() + ' synapses');
-
- $('.notice.metamaps').html(nString + sString + ' you created updated to ' + permission)
- setTimeout(function () {
- $('.notice.metamaps').fadeOut('fast');
- }, 8000);
}
\ No newline at end of file
diff --git a/app/assets/javascripts/Jit/jit2.0.0.js b/app/assets/javascripts/Jit/jit2.0.0.js
index 60cdb91c..b8fc1bbe 100644
--- a/app/assets/javascripts/Jit/jit2.0.0.js
+++ b/app/assets/javascripts/Jit/jit2.0.0.js
@@ -7238,7 +7238,7 @@ Graph.Label.Native = new Class({
function splitLine(st,n) {var b = ''; var s = st;while (s.length > n) {var c = s.substring(0,n);var d = c.lastIndexOf(' ');var e =c.lastIndexOf('\n');if (e != -1) d = e; if (d == -1) d = n; b += c.substring(0,d) + '\n';s = s.substring(d+1);}return b+s;}
var arrayOfLabelLines = splitLine(node.name,30).split('\n');
//render background
- ctx.fillStyle = 'rgba(24,32,46, 1)';
+ ctx.fillStyle = 'rgba(24, 32, 46, 1)';
ctx.strokeStyle = node.getData('whiteCircle') ? '#FFF' : 'rgba(24,32,46, 1)';
ctx.lineWidth = 2;
var height = 25 * arrayOfLabelLines.length; //font size + margin
diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js
index f07ea1d8..c47c793f 100644
--- a/app/assets/javascripts/application.js
+++ b/app/assets/javascripts/application.js
@@ -20,7 +20,17 @@
//= require jquery.roundabout.min
//= require bip
//= require jquery_ujs
-//= require_tree .
+//= require hogan-2.0.0
+//= require socket.io
+//= require typeahead
+//= require underscore
+//= require backbone
+//= require_directory ./carousel
+// require_directory ./Jit
+//= require_directory ./jquery
+//= require_directory ./realtime
+//= require_directory ./scroll
+//= require_directory ./typing
// other options are 'graph'
var viewMode = "list";
@@ -165,70 +175,6 @@ function updateMetacode(node, metacode) {
});
}
-function updateTopicPermission(node, permission) {
- var mdata = {
- "topic": {
- "permission": permission
- }
- };
- $.ajax({
- type: "PUT",
- dataType: 'json',
- url: "/topics/" + node.id,
- data: mdata,
- success: function (data) {
- $('.showcard .mapPerm').removeClass('co pu pr minimize').addClass(permission.substring(0, 2));
- $('.permissionSelect').remove();
- node.setData("permission", permission);
- },
- error: function () {
- alert('failed to update permission');
- }
- });
-}
-
-function updateSynapsePermission(edge, permission) {
- var mdata = {
- "synapse": {
- "permission": permission
- }
- };
- $.ajax({
- type: "PUT",
- dataType: 'json',
- url: "/synapses/" + edge.data.$id,
- data: mdata,
- success: function (data) {
- $('#edit_synapse .mapPerm').removeClass('co pu pr minimize').addClass(permission.substring(0, 2));
- $('#edit_synapse .permissionSelect').remove();
- edge.setData("permission", permission);
- },
- error: function () {
- alert('failed to update permission');
- }
- });
-}
-
-function updateMapPermission(mapid, permission) {
- var mdata = {
- "map": {
- "permission": permission
- }
- };
- $.ajax({
- type: "PUT",
- dataType: 'json',
- url: "/maps/" + mapid,
- data: mdata,
- success: function (data) {
- $('.mapPermission').removeClass('commons public private minimize').addClass(permission);
- $('.mapPermission .permissionSelect').remove();
- },
- error: function () {
- alert('failed to update permission');
- }
- });
-}
function updateMetacodeSet(set, index, custom) {
@@ -330,21 +276,6 @@ function MconsoleReset() {
Mconsole.canvas.scale((1 / mX), (1 / mY));
}
-function openNodeShowcard(node) {
- //populate the card that's about to show with the right topics data
- populateShowCard(node);
-
- $('.showcard').fadeIn('fast');
- var s = $('.showcard').find('.scroll');
- s.height(s.height()).mCustomScrollbar({
- mouseWheelPixels: 200,
- advanced: {
- updateOnContentResize: true
- }
- });
- MetamapsModel.showcardInUse = node.id;
-}
-
function openLightbox(which) {
$('.lightboxContent').hide();
$('#' + which).show();
diff --git a/app/assets/javascripts/backbone.js b/app/assets/javascripts/backbone.js
new file mode 100644
index 00000000..a0726ee4
--- /dev/null
+++ b/app/assets/javascripts/backbone.js
@@ -0,0 +1,1571 @@
+// Backbone.js 1.0.0
+
+// (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
+// Backbone may be freely distributed under the MIT license.
+// For all details and documentation:
+// http://backbonejs.org
+
+(function(){
+
+ // Initial Setup
+ // -------------
+
+ // Save a reference to the global object (`window` in the browser, `exports`
+ // on the server).
+ var root = this;
+
+ // Save the previous value of the `Backbone` variable, so that it can be
+ // restored later on, if `noConflict` is used.
+ var previousBackbone = root.Backbone;
+
+ // Create local references to array methods we'll want to use later.
+ var array = [];
+ var push = array.push;
+ var slice = array.slice;
+ var splice = array.splice;
+
+ // The top-level namespace. All public Backbone classes and modules will
+ // be attached to this. Exported for both the browser and the server.
+ var Backbone;
+ if (typeof exports !== 'undefined') {
+ Backbone = exports;
+ } else {
+ Backbone = root.Backbone = {};
+ }
+
+ // Current version of the library. Keep in sync with `package.json`.
+ Backbone.VERSION = '1.0.0';
+
+ // Require Underscore, if we're on the server, and it's not already present.
+ var _ = root._;
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
+
+ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
+ // the `$` variable.
+ Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
+
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
+ // to its previous owner. Returns a reference to this Backbone object.
+ Backbone.noConflict = function() {
+ root.Backbone = previousBackbone;
+ return this;
+ };
+
+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
+ // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
+ // set a `X-Http-Method-Override` header.
+ Backbone.emulateHTTP = false;
+
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
+ // `application/json` requests ... will encode the body as
+ // `application/x-www-form-urlencoded` instead and will send the model in a
+ // form param named `model`.
+ Backbone.emulateJSON = false;
+
+ // Backbone.Events
+ // ---------------
+
+ // A module that can be mixed in to *any object* in order to provide it with
+ // custom events. You may bind with `on` or remove with `off` callback
+ // functions to an event; `trigger`-ing an event fires all callbacks in
+ // succession.
+ //
+ // var object = {};
+ // _.extend(object, Backbone.Events);
+ // object.on('expand', function(){ alert('expanded'); });
+ // object.trigger('expand');
+ //
+ var Events = Backbone.Events = {
+
+ // Bind an event to a `callback` function. Passing `"all"` will bind
+ // the callback to all events fired.
+ on: function(name, callback, context) {
+ if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
+ this._events || (this._events = {});
+ var events = this._events[name] || (this._events[name] = []);
+ events.push({callback: callback, context: context, ctx: context || this});
+ return this;
+ },
+
+ // Bind an event to only be triggered a single time. After the first time
+ // the callback is invoked, it will be removed.
+ once: function(name, callback, context) {
+ if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
+ var self = this;
+ var once = _.once(function() {
+ self.off(name, once);
+ callback.apply(this, arguments);
+ });
+ once._callback = callback;
+ return this.on(name, once, context);
+ },
+
+ // Remove one or many callbacks. If `context` is null, removes all
+ // callbacks with that function. If `callback` is null, removes all
+ // callbacks for the event. If `name` is null, removes all bound
+ // callbacks for all events.
+ off: function(name, callback, context) {
+ var retain, ev, events, names, i, l, j, k;
+ if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
+ if (!name && !callback && !context) {
+ this._events = {};
+ return this;
+ }
+
+ names = name ? [name] : _.keys(this._events);
+ for (i = 0, l = names.length; i < l; i++) {
+ name = names[i];
+ if (events = this._events[name]) {
+ this._events[name] = retain = [];
+ if (callback || context) {
+ for (j = 0, k = events.length; j < k; j++) {
+ ev = events[j];
+ if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
+ (context && context !== ev.context)) {
+ retain.push(ev);
+ }
+ }
+ }
+ if (!retain.length) delete this._events[name];
+ }
+ }
+
+ return this;
+ },
+
+ // Trigger one or many events, firing all bound callbacks. Callbacks are
+ // passed the same arguments as `trigger` is, apart from the event name
+ // (unless you're listening on `"all"`, which will cause your callback to
+ // receive the true name of the event as the first argument).
+ trigger: function(name) {
+ if (!this._events) return this;
+ var args = slice.call(arguments, 1);
+ if (!eventsApi(this, 'trigger', name, args)) return this;
+ var events = this._events[name];
+ var allEvents = this._events.all;
+ if (events) triggerEvents(events, args);
+ if (allEvents) triggerEvents(allEvents, arguments);
+ return this;
+ },
+
+ // Tell this object to stop listening to either specific events ... or
+ // to every object it's currently listening to.
+ stopListening: function(obj, name, callback) {
+ var listeners = this._listeners;
+ if (!listeners) return this;
+ var deleteListener = !name && !callback;
+ if (typeof name === 'object') callback = this;
+ if (obj) (listeners = {})[obj._listenerId] = obj;
+ for (var id in listeners) {
+ listeners[id].off(name, callback, this);
+ if (deleteListener) delete this._listeners[id];
+ }
+ return this;
+ }
+
+ };
+
+ // Regular expression used to split event strings.
+ var eventSplitter = /\s+/;
+
+ // Implement fancy features of the Events API such as multiple event
+ // names `"change blur"` and jQuery-style event maps `{change: action}`
+ // in terms of the existing API.
+ var eventsApi = function(obj, action, name, rest) {
+ if (!name) return true;
+
+ // Handle event maps.
+ if (typeof name === 'object') {
+ for (var key in name) {
+ obj[action].apply(obj, [key, name[key]].concat(rest));
+ }
+ return false;
+ }
+
+ // Handle space separated event names.
+ if (eventSplitter.test(name)) {
+ var names = name.split(eventSplitter);
+ for (var i = 0, l = names.length; i < l; i++) {
+ obj[action].apply(obj, [names[i]].concat(rest));
+ }
+ return false;
+ }
+
+ return true;
+ };
+
+ // A difficult-to-believe, but optimized internal dispatch function for
+ // triggering events. Tries to keep the usual cases speedy (most internal
+ // Backbone events have 3 arguments).
+ var triggerEvents = function(events, args) {
+ var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
+ switch (args.length) {
+ case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
+ case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
+ case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
+ case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
+ default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
+ }
+ };
+
+ var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
+
+ // Inversion-of-control versions of `on` and `once`. Tell *this* object to
+ // listen to an event in another object ... keeping track of what it's
+ // listening to.
+ _.each(listenMethods, function(implementation, method) {
+ Events[method] = function(obj, name, callback) {
+ var listeners = this._listeners || (this._listeners = {});
+ var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
+ listeners[id] = obj;
+ if (typeof name === 'object') callback = this;
+ obj[implementation](name, callback, this);
+ return this;
+ };
+ });
+
+ // Aliases for backwards compatibility.
+ Events.bind = Events.on;
+ Events.unbind = Events.off;
+
+ // Allow the `Backbone` object to serve as a global event bus, for folks who
+ // want global "pubsub" in a convenient place.
+ _.extend(Backbone, Events);
+
+ // Backbone.Model
+ // --------------
+
+ // Backbone **Models** are the basic data object in the framework --
+ // frequently representing a row in a table in a database on your server.
+ // A discrete chunk of data and a bunch of useful, related methods for
+ // performing computations and transformations on that data.
+
+ // Create a new model with the specified attributes. A client id (`cid`)
+ // is automatically generated and assigned for you.
+ var Model = Backbone.Model = function(attributes, options) {
+ var defaults;
+ var attrs = attributes || {};
+ options || (options = {});
+ this.cid = _.uniqueId('c');
+ this.attributes = {};
+ _.extend(this, _.pick(options, modelOptions));
+ if (options.parse) attrs = this.parse(attrs, options) || {};
+ if (defaults = _.result(this, 'defaults')) {
+ attrs = _.defaults({}, attrs, defaults);
+ }
+ this.set(attrs, options);
+ this.changed = {};
+ this.initialize.apply(this, arguments);
+ };
+
+ // A list of options to be attached directly to the model, if provided.
+ var modelOptions = ['url', 'urlRoot', 'collection'];
+
+ // Attach all inheritable methods to the Model prototype.
+ _.extend(Model.prototype, Events, {
+
+ // A hash of attributes whose current and previous value differ.
+ changed: null,
+
+ // The value returned during the last failed validation.
+ validationError: null,
+
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
+ // CouchDB users may want to set this to `"_id"`.
+ idAttribute: 'id',
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // Return a copy of the model's `attributes` object.
+ toJSON: function(options) {
+ return _.clone(this.attributes);
+ },
+
+ // Proxy `Backbone.sync` by default -- but override this if you need
+ // custom syncing semantics for *this* particular model.
+ sync: function() {
+ return Backbone.sync.apply(this, arguments);
+ },
+
+ // Get the value of an attribute.
+ get: function(attr) {
+ return this.attributes[attr];
+ },
+
+ // Get the HTML-escaped value of an attribute.
+ escape: function(attr) {
+ return _.escape(this.get(attr));
+ },
+
+ // Returns `true` if the attribute contains a value that is not null
+ // or undefined.
+ has: function(attr) {
+ return this.get(attr) != null;
+ },
+
+ // Set a hash of model attributes on the object, firing `"change"`. This is
+ // the core primitive operation of a model, updating the data and notifying
+ // anyone who needs to know about the change in state. The heart of the beast.
+ set: function(key, val, options) {
+ var attr, attrs, unset, changes, silent, changing, prev, current;
+ if (key == null) return this;
+
+ // Handle both `"key", value` and `{key: value}` -style arguments.
+ if (typeof key === 'object') {
+ attrs = key;
+ options = val;
+ } else {
+ (attrs = {})[key] = val;
+ }
+
+ options || (options = {});
+
+ // Run validation.
+ if (!this._validate(attrs, options)) return false;
+
+ // Extract attributes and options.
+ unset = options.unset;
+ silent = options.silent;
+ changes = [];
+ changing = this._changing;
+ this._changing = true;
+
+ if (!changing) {
+ this._previousAttributes = _.clone(this.attributes);
+ this.changed = {};
+ }
+ current = this.attributes, prev = this._previousAttributes;
+
+ // Check for changes of `id`.
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
+
+ // For each `set` attribute, update or delete the current value.
+ for (attr in attrs) {
+ val = attrs[attr];
+ if (!_.isEqual(current[attr], val)) changes.push(attr);
+ if (!_.isEqual(prev[attr], val)) {
+ this.changed[attr] = val;
+ } else {
+ delete this.changed[attr];
+ }
+ unset ? delete current[attr] : current[attr] = val;
+ }
+
+ // Trigger all relevant attribute changes.
+ if (!silent) {
+ if (changes.length) this._pending = true;
+ for (var i = 0, l = changes.length; i < l; i++) {
+ this.trigger('change:' + changes[i], this, current[changes[i]], options);
+ }
+ }
+
+ // You might be wondering why there's a `while` loop here. Changes can
+ // be recursively nested within `"change"` events.
+ if (changing) return this;
+ if (!silent) {
+ while (this._pending) {
+ this._pending = false;
+ this.trigger('change', this, options);
+ }
+ }
+ this._pending = false;
+ this._changing = false;
+ return this;
+ },
+
+ // Remove an attribute from the model, firing `"change"`. `unset` is a noop
+ // if the attribute doesn't exist.
+ unset: function(attr, options) {
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
+ },
+
+ // Clear all attributes on the model, firing `"change"`.
+ clear: function(options) {
+ var attrs = {};
+ for (var key in this.attributes) attrs[key] = void 0;
+ return this.set(attrs, _.extend({}, options, {unset: true}));
+ },
+
+ // Determine if the model has changed since the last `"change"` event.
+ // If you specify an attribute name, determine if that attribute has changed.
+ hasChanged: function(attr) {
+ if (attr == null) return !_.isEmpty(this.changed);
+ return _.has(this.changed, attr);
+ },
+
+ // Return an object containing all the attributes that have changed, or
+ // false if there are no changed attributes. Useful for determining what
+ // parts of a view need to be updated and/or what attributes need to be
+ // persisted to the server. Unset attributes will be set to undefined.
+ // You can also pass an attributes object to diff against the model,
+ // determining if there *would be* a change.
+ changedAttributes: function(diff) {
+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
+ var val, changed = false;
+ var old = this._changing ? this._previousAttributes : this.attributes;
+ for (var attr in diff) {
+ if (_.isEqual(old[attr], (val = diff[attr]))) continue;
+ (changed || (changed = {}))[attr] = val;
+ }
+ return changed;
+ },
+
+ // Get the previous value of an attribute, recorded at the time the last
+ // `"change"` event was fired.
+ previous: function(attr) {
+ if (attr == null || !this._previousAttributes) return null;
+ return this._previousAttributes[attr];
+ },
+
+ // Get all of the attributes of the model at the time of the previous
+ // `"change"` event.
+ previousAttributes: function() {
+ return _.clone(this._previousAttributes);
+ },
+
+ // Fetch the model from the server. If the server's representation of the
+ // model differs from its current attributes, they will be overridden,
+ // triggering a `"change"` event.
+ fetch: function(options) {
+ options = options ? _.clone(options) : {};
+ if (options.parse === void 0) options.parse = true;
+ var model = this;
+ var success = options.success;
+ options.success = function(resp) {
+ if (!model.set(model.parse(resp, options), options)) return false;
+ if (success) success(model, resp, options);
+ model.trigger('sync', model, resp, options);
+ };
+ wrapError(this, options);
+ return this.sync('read', this, options);
+ },
+
+ // Set a hash of model attributes, and sync the model to the server.
+ // If the server returns an attributes hash that differs, the model's
+ // state will be `set` again.
+ save: function(key, val, options) {
+ var attrs, method, xhr, attributes = this.attributes;
+
+ // Handle both `"key", value` and `{key: value}` -style arguments.
+ if (key == null || typeof key === 'object') {
+ attrs = key;
+ options = val;
+ } else {
+ (attrs = {})[key] = val;
+ }
+
+ // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
+ if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
+
+ options = _.extend({validate: true}, options);
+
+ // Do not persist invalid models.
+ if (!this._validate(attrs, options)) return false;
+
+ // Set temporary attributes if `{wait: true}`.
+ if (attrs && options.wait) {
+ this.attributes = _.extend({}, attributes, attrs);
+ }
+
+ // After a successful server-side save, the client is (optionally)
+ // updated with the server-side state.
+ if (options.parse === void 0) options.parse = true;
+ var model = this;
+ var success = options.success;
+ options.success = function(resp) {
+ // Ensure attributes are restored during synchronous saves.
+ model.attributes = attributes;
+ var serverAttrs = model.parse(resp, options);
+ if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
+ if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
+ return false;
+ }
+ if (success) success(model, resp, options);
+ model.trigger('sync', model, resp, options);
+ };
+ wrapError(this, options);
+
+ method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
+ if (method === 'patch') options.attrs = attrs;
+ xhr = this.sync(method, this, options);
+
+ // Restore attributes.
+ if (attrs && options.wait) this.attributes = attributes;
+
+ return xhr;
+ },
+
+ // Destroy this model on the server if it was already persisted.
+ // Optimistically removes the model from its collection, if it has one.
+ // If `wait: true` is passed, waits for the server to respond before removal.
+ destroy: function(options) {
+ options = options ? _.clone(options) : {};
+ var model = this;
+ var success = options.success;
+
+ var destroy = function() {
+ model.trigger('destroy', model, model.collection, options);
+ };
+
+ options.success = function(resp) {
+ if (options.wait || model.isNew()) destroy();
+ if (success) success(model, resp, options);
+ if (!model.isNew()) model.trigger('sync', model, resp, options);
+ };
+
+ if (this.isNew()) {
+ options.success();
+ return false;
+ }
+ wrapError(this, options);
+
+ var xhr = this.sync('delete', this, options);
+ if (!options.wait) destroy();
+ return xhr;
+ },
+
+ // Default URL for the model's representation on the server -- if you're
+ // using Backbone's restful methods, override this to change the endpoint
+ // that will be called.
+ url: function() {
+ var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
+ if (this.isNew()) return base;
+ return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
+ },
+
+ // **parse** converts a response into the hash of attributes to be `set` on
+ // the model. The default implementation is just to pass the response along.
+ parse: function(resp, options) {
+ return resp;
+ },
+
+ // Create a new model with identical attributes to this one.
+ clone: function() {
+ return new this.constructor(this.attributes);
+ },
+
+ // A model is new if it has never been saved to the server, and lacks an id.
+ isNew: function() {
+ return this.id == null;
+ },
+
+ // Check if the model is currently in a valid state.
+ isValid: function(options) {
+ return this._validate({}, _.extend(options || {}, { validate: true }));
+ },
+
+ // Run validation against the next complete set of model attributes,
+ // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
+ _validate: function(attrs, options) {
+ if (!options.validate || !this.validate) return true;
+ attrs = _.extend({}, this.attributes, attrs);
+ var error = this.validationError = this.validate(attrs, options) || null;
+ if (!error) return true;
+ this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
+ return false;
+ }
+
+ });
+
+ // Underscore methods that we want to implement on the Model.
+ var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
+
+ // Mix in each Underscore method as a proxy to `Model#attributes`.
+ _.each(modelMethods, function(method) {
+ Model.prototype[method] = function() {
+ var args = slice.call(arguments);
+ args.unshift(this.attributes);
+ return _[method].apply(_, args);
+ };
+ });
+
+ // Backbone.Collection
+ // -------------------
+
+ // If models tend to represent a single row of data, a Backbone Collection is
+ // more analagous to a table full of data ... or a small slice or page of that
+ // table, or a collection of rows that belong together for a particular reason
+ // -- all of the messages in this particular folder, all of the documents
+ // belonging to this particular author, and so on. Collections maintain
+ // indexes of their models, both in order, and for lookup by `id`.
+
+ // Create a new **Collection**, perhaps to contain a specific type of `model`.
+ // If a `comparator` is specified, the Collection will maintain
+ // its models in sort order, as they're added and removed.
+ var Collection = Backbone.Collection = function(models, options) {
+ options || (options = {});
+ if (options.url) this.url = options.url;
+ if (options.model) this.model = options.model;
+ if (options.comparator !== void 0) this.comparator = options.comparator;
+ this._reset();
+ this.initialize.apply(this, arguments);
+ if (models) this.reset(models, _.extend({silent: true}, options));
+ };
+
+ // Default options for `Collection#set`.
+ var setOptions = {add: true, remove: true, merge: true};
+ var addOptions = {add: true, merge: false, remove: false};
+
+ // Define the Collection's inheritable methods.
+ _.extend(Collection.prototype, Events, {
+
+ // The default model for a collection is just a **Backbone.Model**.
+ // This should be overridden in most cases.
+ model: Model,
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // The JSON representation of a Collection is an array of the
+ // models' attributes.
+ toJSON: function(options) {
+ return this.map(function(model){ return model.toJSON(options); });
+ },
+
+ // Proxy `Backbone.sync` by default.
+ sync: function() {
+ return Backbone.sync.apply(this, arguments);
+ },
+
+ // Add a model, or list of models to the set.
+ add: function(models, options) {
+ return this.set(models, _.defaults(options || {}, addOptions));
+ },
+
+ // Remove a model, or a list of models from the set.
+ remove: function(models, options) {
+ models = _.isArray(models) ? models.slice() : [models];
+ options || (options = {});
+ var i, l, index, model;
+ for (i = 0, l = models.length; i < l; i++) {
+ model = this.get(models[i]);
+ if (!model) continue;
+ delete this._byId[model.id];
+ delete this._byId[model.cid];
+ index = this.indexOf(model);
+ this.models.splice(index, 1);
+ this.length--;
+ if (!options.silent) {
+ options.index = index;
+ model.trigger('remove', model, this, options);
+ }
+ this._removeReference(model);
+ }
+ return this;
+ },
+
+ // Update a collection by `set`-ing a new list of models, adding new ones,
+ // removing models that are no longer present, and merging models that
+ // already exist in the collection, as necessary. Similar to **Model#set**,
+ // the core operation for updating the data contained by the collection.
+ set: function(models, options) {
+ options = _.defaults(options || {}, setOptions);
+ if (options.parse) models = this.parse(models, options);
+ if (!_.isArray(models)) models = models ? [models] : [];
+ var i, l, model, attrs, existing, sort;
+ var at = options.at;
+ var sortable = this.comparator && (at == null) && options.sort !== false;
+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
+ var toAdd = [], toRemove = [], modelMap = {};
+
+ // Turn bare objects into model references, and prevent invalid models
+ // from being added.
+ for (i = 0, l = models.length; i < l; i++) {
+ if (!(model = this._prepareModel(models[i], options))) continue;
+
+ // If a duplicate is found, prevent it from being added and
+ // optionally merge it into the existing model.
+ if (existing = this.get(model)) {
+ if (options.remove) modelMap[existing.cid] = true;
+ if (options.merge) {
+ existing.set(model.attributes, options);
+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
+ }
+
+ // This is a new model, push it to the `toAdd` list.
+ } else if (options.add) {
+ toAdd.push(model);
+
+ // Listen to added models' events, and index models for lookup by
+ // `id` and by `cid`.
+ model.on('all', this._onModelEvent, this);
+ this._byId[model.cid] = model;
+ if (model.id != null) this._byId[model.id] = model;
+ }
+ }
+
+ // Remove nonexistent models if appropriate.
+ if (options.remove) {
+ for (i = 0, l = this.length; i < l; ++i) {
+ if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
+ }
+ if (toRemove.length) this.remove(toRemove, options);
+ }
+
+ // See if sorting is needed, update `length` and splice in new models.
+ if (toAdd.length) {
+ if (sortable) sort = true;
+ this.length += toAdd.length;
+ if (at != null) {
+ splice.apply(this.models, [at, 0].concat(toAdd));
+ } else {
+ push.apply(this.models, toAdd);
+ }
+ }
+
+ // Silently sort the collection if appropriate.
+ if (sort) this.sort({silent: true});
+
+ if (options.silent) return this;
+
+ // Trigger `add` events.
+ for (i = 0, l = toAdd.length; i < l; i++) {
+ (model = toAdd[i]).trigger('add', model, this, options);
+ }
+
+ // Trigger `sort` if the collection was sorted.
+ if (sort) this.trigger('sort', this, options);
+ return this;
+ },
+
+ // When you have more items than you want to add or remove individually,
+ // you can reset the entire set with a new list of models, without firing
+ // any granular `add` or `remove` events. Fires `reset` when finished.
+ // Useful for bulk operations and optimizations.
+ reset: function(models, options) {
+ options || (options = {});
+ for (var i = 0, l = this.models.length; i < l; i++) {
+ this._removeReference(this.models[i]);
+ }
+ options.previousModels = this.models;
+ this._reset();
+ this.add(models, _.extend({silent: true}, options));
+ if (!options.silent) this.trigger('reset', this, options);
+ return this;
+ },
+
+ // Add a model to the end of the collection.
+ push: function(model, options) {
+ model = this._prepareModel(model, options);
+ this.add(model, _.extend({at: this.length}, options));
+ return model;
+ },
+
+ // Remove a model from the end of the collection.
+ pop: function(options) {
+ var model = this.at(this.length - 1);
+ this.remove(model, options);
+ return model;
+ },
+
+ // Add a model to the beginning of the collection.
+ unshift: function(model, options) {
+ model = this._prepareModel(model, options);
+ this.add(model, _.extend({at: 0}, options));
+ return model;
+ },
+
+ // Remove a model from the beginning of the collection.
+ shift: function(options) {
+ var model = this.at(0);
+ this.remove(model, options);
+ return model;
+ },
+
+ // Slice out a sub-array of models from the collection.
+ slice: function(begin, end) {
+ return this.models.slice(begin, end);
+ },
+
+ // Get a model from the set by id.
+ get: function(obj) {
+ if (obj == null) return void 0;
+ return this._byId[obj.id != null ? obj.id : obj.cid || obj];
+ },
+
+ // Get the model at the given index.
+ at: function(index) {
+ return this.models[index];
+ },
+
+ // Return models with matching attributes. Useful for simple cases of
+ // `filter`.
+ where: function(attrs, first) {
+ if (_.isEmpty(attrs)) return first ? void 0 : [];
+ return this[first ? 'find' : 'filter'](function(model) {
+ for (var key in attrs) {
+ if (attrs[key] !== model.get(key)) return false;
+ }
+ return true;
+ });
+ },
+
+ // Return the first model with matching attributes. Useful for simple cases
+ // of `find`.
+ findWhere: function(attrs) {
+ return this.where(attrs, true);
+ },
+
+ // Force the collection to re-sort itself. You don't need to call this under
+ // normal circumstances, as the set will maintain sort order as each item
+ // is added.
+ sort: function(options) {
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
+ options || (options = {});
+
+ // Run sort based on type of `comparator`.
+ if (_.isString(this.comparator) || this.comparator.length === 1) {
+ this.models = this.sortBy(this.comparator, this);
+ } else {
+ this.models.sort(_.bind(this.comparator, this));
+ }
+
+ if (!options.silent) this.trigger('sort', this, options);
+ return this;
+ },
+
+ // Figure out the smallest index at which a model should be inserted so as
+ // to maintain order.
+ sortedIndex: function(model, value, context) {
+ value || (value = this.comparator);
+ var iterator = _.isFunction(value) ? value : function(model) {
+ return model.get(value);
+ };
+ return _.sortedIndex(this.models, model, iterator, context);
+ },
+
+ // Pluck an attribute from each model in the collection.
+ pluck: function(attr) {
+ return _.invoke(this.models, 'get', attr);
+ },
+
+ // Fetch the default set of models for this collection, resetting the
+ // collection when they arrive. If `reset: true` is passed, the response
+ // data will be passed through the `reset` method instead of `set`.
+ fetch: function(options) {
+ options = options ? _.clone(options) : {};
+ if (options.parse === void 0) options.parse = true;
+ var success = options.success;
+ var collection = this;
+ options.success = function(resp) {
+ var method = options.reset ? 'reset' : 'set';
+ collection[method](resp, options);
+ if (success) success(collection, resp, options);
+ collection.trigger('sync', collection, resp, options);
+ };
+ wrapError(this, options);
+ return this.sync('read', this, options);
+ },
+
+ // Create a new instance of a model in this collection. Add the model to the
+ // collection immediately, unless `wait: true` is passed, in which case we
+ // wait for the server to agree.
+ create: function(model, options) {
+ options = options ? _.clone(options) : {};
+ if (!(model = this._prepareModel(model, options))) return false;
+ if (!options.wait) this.add(model, options);
+ var collection = this;
+ var success = options.success;
+ options.success = function(resp) {
+ if (options.wait) collection.add(model, options);
+ if (success) success(model, resp, options);
+ };
+ model.save(null, options);
+ return model;
+ },
+
+ // **parse** converts a response into a list of models to be added to the
+ // collection. The default implementation is just to pass it through.
+ parse: function(resp, options) {
+ return resp;
+ },
+
+ // Create a new collection with an identical list of models as this one.
+ clone: function() {
+ return new this.constructor(this.models);
+ },
+
+ // Private method to reset all internal state. Called when the collection
+ // is first initialized or reset.
+ _reset: function() {
+ this.length = 0;
+ this.models = [];
+ this._byId = {};
+ },
+
+ // Prepare a hash of attributes (or other model) to be added to this
+ // collection.
+ _prepareModel: function(attrs, options) {
+ if (attrs instanceof Model) {
+ if (!attrs.collection) attrs.collection = this;
+ return attrs;
+ }
+ options || (options = {});
+ options.collection = this;
+ var model = new this.model(attrs, options);
+ if (!model._validate(attrs, options)) {
+ this.trigger('invalid', this, attrs, options);
+ return false;
+ }
+ return model;
+ },
+
+ // Internal method to sever a model's ties to a collection.
+ _removeReference: function(model) {
+ if (this === model.collection) delete model.collection;
+ model.off('all', this._onModelEvent, this);
+ },
+
+ // Internal method called every time a model in the set fires an event.
+ // Sets need to update their indexes when models change ids. All other
+ // events simply proxy through. "add" and "remove" events that originate
+ // in other collections are ignored.
+ _onModelEvent: function(event, model, collection, options) {
+ if ((event === 'add' || event === 'remove') && collection !== this) return;
+ if (event === 'destroy') this.remove(model, options);
+ if (model && event === 'change:' + model.idAttribute) {
+ delete this._byId[model.previous(model.idAttribute)];
+ if (model.id != null) this._byId[model.id] = model;
+ }
+ this.trigger.apply(this, arguments);
+ }
+
+ });
+
+ // Underscore methods that we want to implement on the Collection.
+ // 90% of the core usefulness of Backbone Collections is actually implemented
+ // right here:
+ var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
+ 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
+ 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
+ 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
+ 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
+ 'isEmpty', 'chain'];
+
+ // Mix in each Underscore method as a proxy to `Collection#models`.
+ _.each(methods, function(method) {
+ Collection.prototype[method] = function() {
+ var args = slice.call(arguments);
+ args.unshift(this.models);
+ return _[method].apply(_, args);
+ };
+ });
+
+ // Underscore methods that take a property name as an argument.
+ var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
+
+ // Use attributes instead of properties.
+ _.each(attributeMethods, function(method) {
+ Collection.prototype[method] = function(value, context) {
+ var iterator = _.isFunction(value) ? value : function(model) {
+ return model.get(value);
+ };
+ return _[method](this.models, iterator, context);
+ };
+ });
+
+ // Backbone.View
+ // -------------
+
+ // Backbone Views are almost more convention than they are actual code. A View
+ // is simply a JavaScript object that represents a logical chunk of UI in the
+ // DOM. This might be a single item, an entire list, a sidebar or panel, or
+ // even the surrounding frame which wraps your whole app. Defining a chunk of
+ // UI as a **View** allows you to define your DOM events declaratively, without
+ // having to worry about render order ... and makes it easy for the view to
+ // react to specific changes in the state of your models.
+
+ // Creating a Backbone.View creates its initial element outside of the DOM,
+ // if an existing element is not provided...
+ var View = Backbone.View = function(options) {
+ this.cid = _.uniqueId('view');
+ this._configure(options || {});
+ this._ensureElement();
+ this.initialize.apply(this, arguments);
+ this.delegateEvents();
+ };
+
+ // Cached regex to split keys for `delegate`.
+ var delegateEventSplitter = /^(\S+)\s*(.*)$/;
+
+ // List of view options to be merged as properties.
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
+
+ // Set up all inheritable **Backbone.View** properties and methods.
+ _.extend(View.prototype, Events, {
+
+ // The default `tagName` of a View's element is `"div"`.
+ tagName: 'div',
+
+ // jQuery delegate for element lookup, scoped to DOM elements within the
+ // current view. This should be prefered to global lookups where possible.
+ $: function(selector) {
+ return this.$el.find(selector);
+ },
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // **render** is the core function that your view should override, in order
+ // to populate its element (`this.el`), with the appropriate HTML. The
+ // convention is for **render** to always return `this`.
+ render: function() {
+ return this;
+ },
+
+ // Remove this view by taking the element out of the DOM, and removing any
+ // applicable Backbone.Events listeners.
+ remove: function() {
+ this.$el.remove();
+ this.stopListening();
+ return this;
+ },
+
+ // Change the view's element (`this.el` property), including event
+ // re-delegation.
+ setElement: function(element, delegate) {
+ if (this.$el) this.undelegateEvents();
+ this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
+ this.el = this.$el[0];
+ if (delegate !== false) this.delegateEvents();
+ return this;
+ },
+
+ // Set callbacks, where `this.events` is a hash of
+ //
+ // *{"event selector": "callback"}*
+ //
+ // {
+ // 'mousedown .title': 'edit',
+ // 'click .button': 'save'
+ // 'click .open': function(e) { ... }
+ // }
+ //
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
+ // Uses event delegation for efficiency.
+ // Omitting the selector binds the event to `this.el`.
+ // This only works for delegate-able events: not `focus`, `blur`, and
+ // not `change`, `submit`, and `reset` in Internet Explorer.
+ delegateEvents: function(events) {
+ if (!(events || (events = _.result(this, 'events')))) return this;
+ this.undelegateEvents();
+ for (var key in events) {
+ var method = events[key];
+ if (!_.isFunction(method)) method = this[events[key]];
+ if (!method) continue;
+
+ var match = key.match(delegateEventSplitter);
+ var eventName = match[1], selector = match[2];
+ method = _.bind(method, this);
+ eventName += '.delegateEvents' + this.cid;
+ if (selector === '') {
+ this.$el.on(eventName, method);
+ } else {
+ this.$el.on(eventName, selector, method);
+ }
+ }
+ return this;
+ },
+
+ // Clears all callbacks previously bound to the view with `delegateEvents`.
+ // You usually don't need to use this, but may wish to if you have multiple
+ // Backbone views attached to the same DOM element.
+ undelegateEvents: function() {
+ this.$el.off('.delegateEvents' + this.cid);
+ return this;
+ },
+
+ // Performs the initial configuration of a View with a set of options.
+ // Keys with special meaning *(e.g. model, collection, id, className)* are
+ // attached directly to the view. See `viewOptions` for an exhaustive
+ // list.
+ _configure: function(options) {
+ if (this.options) options = _.extend({}, _.result(this, 'options'), options);
+ _.extend(this, _.pick(options, viewOptions));
+ this.options = options;
+ },
+
+ // Ensure that the View has a DOM element to render into.
+ // If `this.el` is a string, pass it through `$()`, take the first
+ // matching element, and re-assign it to `el`. Otherwise, create
+ // an element from the `id`, `className` and `tagName` properties.
+ _ensureElement: function() {
+ if (!this.el) {
+ var attrs = _.extend({}, _.result(this, 'attributes'));
+ if (this.id) attrs.id = _.result(this, 'id');
+ if (this.className) attrs['class'] = _.result(this, 'className');
+ var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
+ this.setElement($el, false);
+ } else {
+ this.setElement(_.result(this, 'el'), false);
+ }
+ }
+
+ });
+
+ // Backbone.sync
+ // -------------
+
+ // Override this function to change the manner in which Backbone persists
+ // models to the server. You will be passed the type of request, and the
+ // model in question. By default, makes a RESTful Ajax request
+ // to the model's `url()`. Some possible customizations could be:
+ //
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
+ // * Send up the models as XML instead of JSON.
+ // * Persist models via WebSockets instead of Ajax.
+ //
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
+ // as well as all requests with the body as `application/x-www-form-urlencoded`
+ // instead of `application/json` with the model in a param named `model`.
+ // Useful when interfacing with server-side languages like **PHP** that make
+ // it difficult to read the body of `PUT` requests.
+ Backbone.sync = function(method, model, options) {
+ var type = methodMap[method];
+
+ // Default options, unless specified.
+ _.defaults(options || (options = {}), {
+ emulateHTTP: Backbone.emulateHTTP,
+ emulateJSON: Backbone.emulateJSON
+ });
+
+ // Default JSON-request options.
+ var params = {type: type, dataType: 'json'};
+
+ // Ensure that we have a URL.
+ if (!options.url) {
+ params.url = _.result(model, 'url') || urlError();
+ }
+
+ // Ensure that we have the appropriate request data.
+ if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
+ params.contentType = 'application/json';
+ params.data = JSON.stringify(options.attrs || model.toJSON(options));
+ }
+
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
+ if (options.emulateJSON) {
+ params.contentType = 'application/x-www-form-urlencoded';
+ params.data = params.data ? {model: params.data} : {};
+ }
+
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
+ // And an `X-HTTP-Method-Override` header.
+ if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
+ params.type = 'POST';
+ if (options.emulateJSON) params.data._method = type;
+ var beforeSend = options.beforeSend;
+ options.beforeSend = function(xhr) {
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
+ if (beforeSend) return beforeSend.apply(this, arguments);
+ };
+ }
+
+ // Don't process data on a non-GET request.
+ if (params.type !== 'GET' && !options.emulateJSON) {
+ params.processData = false;
+ }
+
+ // If we're sending a `PATCH` request, and we're in an old Internet Explorer
+ // that still has ActiveX enabled by default, override jQuery to use that
+ // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
+ if (params.type === 'PATCH' && window.ActiveXObject &&
+ !(window.external && window.external.msActiveXFilteringEnabled)) {
+ params.xhr = function() {
+ return new ActiveXObject("Microsoft.XMLHTTP");
+ };
+ }
+
+ // Make the request, allowing the user to override any Ajax options.
+ var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
+ model.trigger('request', model, xhr, options);
+ return xhr;
+ };
+
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
+ var methodMap = {
+ 'create': 'POST',
+ 'update': 'PUT',
+ 'patch': 'PATCH',
+ 'delete': 'DELETE',
+ 'read': 'GET'
+ };
+
+ // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
+ // Override this if you'd like to use a different library.
+ Backbone.ajax = function() {
+ return Backbone.$.ajax.apply(Backbone.$, arguments);
+ };
+
+ // Backbone.Router
+ // ---------------
+
+ // Routers map faux-URLs to actions, and fire events when routes are
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
+ var Router = Backbone.Router = function(options) {
+ options || (options = {});
+ if (options.routes) this.routes = options.routes;
+ this._bindRoutes();
+ this.initialize.apply(this, arguments);
+ };
+
+ // Cached regular expressions for matching named param parts and splatted
+ // parts of route strings.
+ var optionalParam = /\((.*?)\)/g;
+ var namedParam = /(\(\?)?:\w+/g;
+ var splatParam = /\*\w+/g;
+ var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
+
+ // Set up all inheritable **Backbone.Router** properties and methods.
+ _.extend(Router.prototype, Events, {
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // Manually bind a single named route to a callback. For example:
+ //
+ // this.route('search/:query/p:num', 'search', function(query, num) {
+ // ...
+ // });
+ //
+ route: function(route, name, callback) {
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
+ if (_.isFunction(name)) {
+ callback = name;
+ name = '';
+ }
+ if (!callback) callback = this[name];
+ var router = this;
+ Backbone.history.route(route, function(fragment) {
+ var args = router._extractParameters(route, fragment);
+ callback && callback.apply(router, args);
+ router.trigger.apply(router, ['route:' + name].concat(args));
+ router.trigger('route', name, args);
+ Backbone.history.trigger('route', router, name, args);
+ });
+ return this;
+ },
+
+ // Simple proxy to `Backbone.history` to save a fragment into the history.
+ navigate: function(fragment, options) {
+ Backbone.history.navigate(fragment, options);
+ return this;
+ },
+
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
+ // order of the routes here to support behavior where the most general
+ // routes can be defined at the bottom of the route map.
+ _bindRoutes: function() {
+ if (!this.routes) return;
+ this.routes = _.result(this, 'routes');
+ var route, routes = _.keys(this.routes);
+ while ((route = routes.pop()) != null) {
+ this.route(route, this.routes[route]);
+ }
+ },
+
+ // Convert a route string into a regular expression, suitable for matching
+ // against the current location hash.
+ _routeToRegExp: function(route) {
+ route = route.replace(escapeRegExp, '\\$&')
+ .replace(optionalParam, '(?:$1)?')
+ .replace(namedParam, function(match, optional){
+ return optional ? match : '([^\/]+)';
+ })
+ .replace(splatParam, '(.*?)');
+ return new RegExp('^' + route + '$');
+ },
+
+ // Given a route, and a URL fragment that it matches, return the array of
+ // extracted decoded parameters. Empty or unmatched parameters will be
+ // treated as `null` to normalize cross-browser behavior.
+ _extractParameters: function(route, fragment) {
+ var params = route.exec(fragment).slice(1);
+ return _.map(params, function(param) {
+ return param ? decodeURIComponent(param) : null;
+ });
+ }
+
+ });
+
+ // Backbone.History
+ // ----------------
+
+ // Handles cross-browser history management, based on either
+ // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
+ // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
+ // and URL fragments. If the browser supports neither (old IE, natch),
+ // falls back to polling.
+ var History = Backbone.History = function() {
+ this.handlers = [];
+ _.bindAll(this, 'checkUrl');
+
+ // Ensure that `History` can be used outside of the browser.
+ if (typeof window !== 'undefined') {
+ this.location = window.location;
+ this.history = window.history;
+ }
+ };
+
+ // Cached regex for stripping a leading hash/slash and trailing space.
+ var routeStripper = /^[#\/]|\s+$/g;
+
+ // Cached regex for stripping leading and trailing slashes.
+ var rootStripper = /^\/+|\/+$/g;
+
+ // Cached regex for detecting MSIE.
+ var isExplorer = /msie [\w.]+/;
+
+ // Cached regex for removing a trailing slash.
+ var trailingSlash = /\/$/;
+
+ // Has the history handling already been started?
+ History.started = false;
+
+ // Set up all inheritable **Backbone.History** properties and methods.
+ _.extend(History.prototype, Events, {
+
+ // The default interval to poll for hash changes, if necessary, is
+ // twenty times a second.
+ interval: 50,
+
+ // Gets the true hash value. Cannot use location.hash directly due to bug
+ // in Firefox where location.hash will always be decoded.
+ getHash: function(window) {
+ var match = (window || this).location.href.match(/#(.*)$/);
+ return match ? match[1] : '';
+ },
+
+ // Get the cross-browser normalized URL fragment, either from the URL,
+ // the hash, or the override.
+ getFragment: function(fragment, forcePushState) {
+ if (fragment == null) {
+ if (this._hasPushState || !this._wantsHashChange || forcePushState) {
+ fragment = this.location.pathname;
+ var root = this.root.replace(trailingSlash, '');
+ if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
+ } else {
+ fragment = this.getHash();
+ }
+ }
+ return fragment.replace(routeStripper, '');
+ },
+
+ // Start the hash change handling, returning `true` if the current URL matches
+ // an existing route, and `false` otherwise.
+ start: function(options) {
+ if (History.started) throw new Error("Backbone.history has already been started");
+ History.started = true;
+
+ // Figure out the initial configuration. Do we need an iframe?
+ // Is pushState desired ... is it available?
+ this.options = _.extend({}, {root: '/'}, this.options, options);
+ this.root = this.options.root;
+ this._wantsHashChange = this.options.hashChange !== false;
+ this._wantsPushState = !!this.options.pushState;
+ this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
+ var fragment = this.getFragment();
+ var docMode = document.documentMode;
+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
+
+ // Normalize root to always include a leading and trailing slash.
+ this.root = ('/' + this.root + '/').replace(rootStripper, '/');
+
+ if (oldIE && this._wantsHashChange) {
+ this.iframe = Backbone.$('').hide().appendTo('body')[0].contentWindow;
+ this.navigate(fragment);
+ }
+
+ // Depending on whether we're using pushState or hashes, and whether
+ // 'onhashchange' is supported, determine how we check the URL state.
+ if (this._hasPushState) {
+ Backbone.$(window).on('popstate', this.checkUrl);
+ } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
+ Backbone.$(window).on('hashchange', this.checkUrl);
+ } else if (this._wantsHashChange) {
+ this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
+ }
+
+ // Determine if we need to change the base url, for a pushState link
+ // opened by a non-pushState browser.
+ this.fragment = fragment;
+ var loc = this.location;
+ var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
+
+ // If we've started off with a route from a `pushState`-enabled browser,
+ // but we're currently in a browser that doesn't support it...
+ if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
+ this.fragment = this.getFragment(null, true);
+ this.location.replace(this.root + this.location.search + '#' + this.fragment);
+ // Return immediately as browser will do redirect to new url
+ return true;
+
+ // Or if we've started out with a hash-based route, but we're currently
+ // in a browser where it could be `pushState`-based instead...
+ } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
+ this.fragment = this.getHash().replace(routeStripper, '');
+ this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
+ }
+
+ if (!this.options.silent) return this.loadUrl();
+ },
+
+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
+ // but possibly useful for unit testing Routers.
+ stop: function() {
+ Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
+ clearInterval(this._checkUrlInterval);
+ History.started = false;
+ },
+
+ // Add a route to be tested when the fragment changes. Routes added later
+ // may override previous routes.
+ route: function(route, callback) {
+ this.handlers.unshift({route: route, callback: callback});
+ },
+
+ // Checks the current URL to see if it has changed, and if it has,
+ // calls `loadUrl`, normalizing across the hidden iframe.
+ checkUrl: function(e) {
+ var current = this.getFragment();
+ if (current === this.fragment && this.iframe) {
+ current = this.getFragment(this.getHash(this.iframe));
+ }
+ if (current === this.fragment) return false;
+ if (this.iframe) this.navigate(current);
+ this.loadUrl() || this.loadUrl(this.getHash());
+ },
+
+ // Attempt to load the current URL fragment. If a route succeeds with a
+ // match, returns `true`. If no defined routes matches the fragment,
+ // returns `false`.
+ loadUrl: function(fragmentOverride) {
+ var fragment = this.fragment = this.getFragment(fragmentOverride);
+ var matched = _.any(this.handlers, function(handler) {
+ if (handler.route.test(fragment)) {
+ handler.callback(fragment);
+ return true;
+ }
+ });
+ return matched;
+ },
+
+ // Save a fragment into the hash history, or replace the URL state if the
+ // 'replace' option is passed. You are responsible for properly URL-encoding
+ // the fragment in advance.
+ //
+ // The options object can contain `trigger: true` if you wish to have the
+ // route callback be fired (not usually desirable), or `replace: true`, if
+ // you wish to modify the current URL without adding an entry to the history.
+ navigate: function(fragment, options) {
+ if (!History.started) return false;
+ if (!options || options === true) options = {trigger: options};
+ fragment = this.getFragment(fragment || '');
+ if (this.fragment === fragment) return;
+ this.fragment = fragment;
+ var url = this.root + fragment;
+
+ // If pushState is available, we use it to set the fragment as a real URL.
+ if (this._hasPushState) {
+ this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
+
+ // If hash changes haven't been explicitly disabled, update the hash
+ // fragment to store history.
+ } else if (this._wantsHashChange) {
+ this._updateHash(this.location, fragment, options.replace);
+ if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
+ // Opening and closing the iframe tricks IE7 and earlier to push a
+ // history entry on hash-tag change. When replace is true, we don't
+ // want this.
+ if(!options.replace) this.iframe.document.open().close();
+ this._updateHash(this.iframe.location, fragment, options.replace);
+ }
+
+ // If you've told us that you explicitly don't want fallback hashchange-
+ // based history, then `navigate` becomes a page refresh.
+ } else {
+ return this.location.assign(url);
+ }
+ if (options.trigger) this.loadUrl(fragment);
+ },
+
+ // Update the hash location, either replacing the current entry, or adding
+ // a new one to the browser history.
+ _updateHash: function(location, fragment, replace) {
+ if (replace) {
+ var href = location.href.replace(/(javascript:|#).*$/, '');
+ location.replace(href + '#' + fragment);
+ } else {
+ // Some browsers require that `hash` contains a leading #.
+ location.hash = '#' + fragment;
+ }
+ }
+
+ });
+
+ // Create the default Backbone.history.
+ Backbone.history = new History;
+
+ // Helpers
+ // -------
+
+ // Helper function to correctly set up the prototype chain, for subclasses.
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
+ // class properties to be extended.
+ var extend = function(protoProps, staticProps) {
+ var parent = this;
+ var child;
+
+ // The constructor function for the new subclass is either defined by you
+ // (the "constructor" property in your `extend` definition), or defaulted
+ // by us to simply call the parent's constructor.
+ if (protoProps && _.has(protoProps, 'constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ return parent.apply(this, arguments); };
+ }
+
+ // Add static properties to the constructor function, if supplied.
+ _.extend(child, parent, staticProps);
+
+ // Set the prototype chain to inherit from `parent`, without calling
+ // `parent`'s constructor function.
+ var Surrogate = function(){ this.constructor = child; };
+ Surrogate.prototype = parent.prototype;
+ child.prototype = new Surrogate;
+
+ // Add prototype properties (instance properties) to the subclass,
+ // if supplied.
+ if (protoProps) _.extend(child.prototype, protoProps);
+
+ // Set a convenience property in case the parent's prototype is needed
+ // later.
+ child.__super__ = parent.prototype;
+
+ return child;
+ };
+
+ // Set up inheritance for the model, collection, router, view and history.
+ Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
+
+ // Throw an error when a URL is needed, and none is supplied.
+ var urlError = function() {
+ throw new Error('A "url" property or function must be specified');
+ };
+
+ // Wrap an optional error callback with a fallback error event.
+ var wrapError = function (model, options) {
+ var error = options.error;
+ options.error = function(resp) {
+ if (error) error(model, resp, options);
+ model.trigger('error', model, resp, options);
+ };
+ };
+
+}).call(this);
\ No newline at end of file
diff --git a/app/assets/javascripts/carousel/cloud-carousel.1.0.5.js b/app/assets/javascripts/carousel/cloud-carousel.1.0.5.js
index 467ae3c4..8cfe5ae0 100644
--- a/app/assets/javascripts/carousel/cloud-carousel.1.0.5.js
+++ b/app/assets/javascripts/carousel/cloud-carousel.1.0.5.js
@@ -198,7 +198,7 @@ jQuery.browser = browser;
{
$(options.titleBox).html( ($(event.target).attr('title') ));
// METAMAPS CODE
- $('#topic_metacode').val($(event.target).attr('title'));
+ Metamaps.Create.newTopic.metacode = $(event.target).attr('title');
// NOT METAMAPS CODE
var idx = $(event.target).data('itemIndex');
var frontIndex = event.data.frontIndex;
@@ -236,7 +236,7 @@ jQuery.browser = browser;
{
if ( items[this.frontIndex] === undefined ) { return; } // Images might not have loaded yet.
// METAMAPS CODE
- $('#topic_metacode').val($(items[this.frontIndex].image).attr('title'));
+ Metamaps.Create.newTopic.metacode = $(items[this.frontIndex].image).attr('title');
//$('img.cloudcarousel').css({"background":"none", "width":"","height":""});
//$(items[this.frontIndex].image).css({"width":"45px","height":"45px"});
// NOT METAMAPS CODE
diff --git a/app/assets/javascripts/jquery/AllMappingPages.js b/app/assets/javascripts/jquery/AllMappingPages.js
index 3848b068..9fa44041 100644
--- a/app/assets/javascripts/jquery/AllMappingPages.js
+++ b/app/assets/javascripts/jquery/AllMappingPages.js
@@ -57,7 +57,7 @@ $(document).ready(function () {
// hide the other two
$('.sidebarAccountBox').hide();
$('.sidebarCollaborateBox').hide();
- $('.sidebarAccountIcon').css('background-color', '#0F1519');
+ //$('.sidebarAccountIcon').css('background-color', '#0F1519');
$('.sidebarCollaborateIcon').css('background-color', '#0F1519');
$('.sidebarFilterIcon').css('background-color', '#000');
diff --git a/app/assets/javascripts/jquery/AuthCanEditMapPage.js b/app/assets/javascripts/jquery/AuthCanEditMapPage.js
index 6c79ffb3..cdb5c3c5 100644
--- a/app/assets/javascripts/jquery/AuthCanEditMapPage.js
+++ b/app/assets/javascripts/jquery/AuthCanEditMapPage.js
@@ -37,7 +37,7 @@ $(document).ready(function () {
$('.sidebarFilterBox').hide();
$('.sidebarAccountBox').hide();
$('.sidebarFilterIcon').css('background-color', '#0F1519');
- $('.sidebarAccountIcon').css('background-color', '#0F1519');
+ //$('.sidebarAccountIcon').css('background-color', '#0F1519');
$('.sidebarCollaborateIcon').css('background-color', '#000');
$('.sidebarCollaborateBox').fadeIn(200, function () {
@@ -58,7 +58,7 @@ $(document).ready(function () {
var openSave = function () {
// hide the other three
$('.sidebarFilterBox, .sidebarAccountBox, .sidebarCollaborateBox').hide();
- $('.sidebarFilterIcon, .sidebarAccountIcon, .sidebarCollaborateIcon').css('background-color', '#0F1519');
+ $('.sidebarFilterIcon, .sidebarCollaborateIcon').css('background-color', '#0F1519');
}
// bind the hover events
$(".sidebarSave").hover(openSave, closeSave);
diff --git a/app/assets/javascripts/jquery/AuthCanEditMappingPages.js b/app/assets/javascripts/jquery/AuthCanEditMappingPages.js
index 4ec0f72d..c46ac6a5 100644
--- a/app/assets/javascripts/jquery/AuthCanEditMappingPages.js
+++ b/app/assets/javascripts/jquery/AuthCanEditMappingPages.js
@@ -17,7 +17,7 @@ $(document).ready(function () {
var openFork = function () {
// hide the other three
$('.sidebarFilterBox, .sidebarAccountBox, .sidebarCollaborateBox').hide();
- $('.sidebarFilterIcon, .sidebarAccountIcon, .sidebarCollaborateIcon').css('background-color', '#0F1519');
+ $('.sidebarFilterIcon, .sidebarCollaborateIcon').css('background-color', '#0F1519');
}
// bind the hover events
$(".sidebarFork").hover(openFork, closeFork);
@@ -25,137 +25,13 @@ $(document).ready(function () {
// bind hover events
bindForkHover();
-
- //////
- //////
- //// TOPIC CREATION
-
- // initialize the autocomplete results for the metacode spinner
- $('#topic_name').typeahead([
- {
- name: 'topic_autocomplete',
- limit: 8,
- template: $('#topicAutocompleteTemplate').html(),
- remote: {
- url: '/topics/autocomplete_topic?term=%QUERY'
- },
- engine: Hogan
- }
- ]);
-
- var topicTypeahead = false;
- // tell the autocomplete to submit the form with the topic you clicked on if you pick from the autocomplete
- $('#topic_name').bind('typeahead:selected', function (event, datum, dataset) {
- $('#topic_grabTopic').val(datum.id);
- event.preventDefault();
- event.stopPropagation();
- $('.new_topic').submit();
- topicTypeahead = true;
- });
- $('#topic_name').bind('typeahead:opened', function () {
- topicTypeahead = false;
- });
-
- // bind keyboard handlers
- $('#topic_name').bind('keyup', function (e) {
- switch (e.which) {
- case 13:
- if (!topicTypeahead) $('.new_topic').submit();
- break;
- default:
- break;
- }
- });
-
- // initialize metacode spinner and then hide it
- $("#metacodeImg").CloudCarousel({
- titleBox: $('#metacodeImgTitle'),
- yRadius: 40,
- xPos: 150,
- yPos: 40,
- speed: 0.3,
- mouseWheel: true,
- bringToFront: true
- });
- $('.new_topic').hide();
-
-
- //////
- //////
- //// SYNAPSE CREATION
-
- // initialize the autocomplete results for synapse creation
- $('#synapse_desc').typeahead([
- {
- name: 'synapse_autocomplete',
- template: "
';
+ rightclickmenu.innerHTML = menustring;
+
+ // position the menu where the click happened
+ $(rightclickmenu).css({
+ left: e.clientX,
+ top: e.clientY
+ });
+ //add the menu to the page
+ $('#center-container').append(rightclickmenu);
+
+
+ // attach events to clicks on the list items
+
+ // delete the selected things from the database
+ $('.rc-delete').click(function () {
+ $('.rightclickmenu').remove();
+ var n = Metamaps.Selected.Topics.length;
+ var e = Metamaps.Selected.Synapses.length;
+ var ntext = n == 1 ? "1 topic" : n + " topics";
+ var etext = e == 1 ? "1 synapse" : e + " synapses";
+ var text = "You have " + ntext + " and " + etext + " selected. ";
+
+ var r = confirm(text + "Are you sure you want to permanently delete them all? This will remove them from all maps they appear on.");
+ if (r == true) {
+ Metamaps.Control.deleteSelectedEdges();
+ Metamaps.Control.deleteSelectedNodes();
+ }
+ });
+
+ // remove the selected things from the map
+ $('.rc-remove').click(function () {
+ $('.rightclickmenu').remove();
+ Metamaps.Control.removeSelectedEdges();
+ Metamaps.Control.removeSelectedNodes();
+ });
+
+ // hide selected nodes and synapses until refresh
+ $('.rc-hide').click(function () {
+ $('.rightclickmenu').remove();
+ Metamaps.Control.hideSelectedEdges();
+ Metamaps.Control.hideSelectedNodes();
+ });
+
+ // when in radial, center on the topic you picked
+ $('.rc-center').click(function () {
+ $('.rightclickmenu').remove();
+ centerOn(node.id);
+ });
+
+ // open the entity in a new tab
+ $('.rc-popout').click(function () {
+ $('.rightclickmenu').remove();
+ var win = window.open('/topics/' + node.id, '_blank');
+ win.focus();
+ });
+
+ // change the permission of all the selected nodes and synapses that you were the originator of
+ $('.rc-permission li').click(function () {
+ $('.rightclickmenu').remove();
+ // $(this).text() will be 'commons' 'public' or 'private'
+ Metamaps.Control.updateSelectedPermissions($(this).text());
+ });
+
+ }, //selectNodeOnRightClickHandler
+ selectEdgeOnClickHandler: function (adj, e) {
+ if (Metamaps.Visualize.mGraph.busy) return;
+
+ //editing overrides everything else
+ if (e.altKey) {
+ //in select-edit-delete-nodes-and-edges.js
+ // editEdge(adj, e); TODO need to find and reimplement this function
+ return;
+ }
+
+ var edgeIsSelected = Metamaps.Selected.Synapses.indexOf(adj);
+ if (edgeIsSelected == -1) edgeIsSelected = false;
+ else if (edgeIsSelected != -1) edgeIsSelected = true;
+
+ if (edgeIsSelected && e.shiftKey) {
+ //deselecting an edge with shift
+ Metamaps.Control.deselectEdge(adj);
+ } else if (!edgeIsSelected && e.shiftKey) {
+ //selecting an edge with shift
+ Metamaps.Control.selectEdge(adj);
+ } else if (edgeIsSelected && !e.shiftKey) {
+ //deselecting an edge without shift - unselect all
+ Metamaps.Control.deselectAllEdges();
+ } else if (!edgeIsSelected && !e.shiftKey) {
+ //selecting an edge without shift - unselect all but new one
+ Metamaps.Control.deselectAllEdges();
+ Metamaps.Control.selectEdge(adj);
+ }
+
+ Metamaps.Visualize.mGraph.plot();
+ }, //selectEdgeOnClickHandler
+ selectEdgeOnRightClickHandler: function (adj, e) {
+ if (Metamaps.Visualize.mGraph.busy) return;
+
+ console.log('edge right click handler working');
+ }, //selectEdgeOnRightClickHandler
+ SmoothPanning: function () {
+
+ var sx = Metamaps.Visualize.mGraph.canvas.scaleOffsetX,
+ sy = Metamaps.Visualize.mGraph.canvas.scaleOffsetY,
+ y_velocity = Metamaps.Mouse.changeInY, // initial y velocity
+ x_velocity = Metamaps.Mouse.changeInX, // initial x velocity
+ easing = 1; // frictional value
+
+ easing = 1;
+ window.clearInterval(panningInt)
+ panningInt = setInterval(function () {
+ myTimer()
+ }, 1);
+
+ function myTimer() {
+ Metamaps.Visualize.mGraph.canvas.translate(x_velocity * easing * 1 / sx, y_velocity * easing * 1 / sy);
+ easing = easing * 0.75;
+
+ if (easing < 0.1) window.clearInterval(panningInt);
+ }
+ }, // SmoothPanning
+ generateLittleHTML: function (node) {
+ var mapperm = Metamaps.Active.Map.authorizeToEdit(Metamaps.Active.Mapper);
+
+ var littleHTML = '
{{ name }}
';
+
+ if (userid == null || !Metamaps.Active.Map || !mapperm) {
+ //unauthenticated, not on a map: can remove from canvas
+ littleHTML += '';
+ } else if (mapperm) {
+ //permission to remove nodes from the map
+ littleHTML += '';
+ }
+
+ if (userid == node.getData('userid')) {
+ //logged in, and owner of the topic, thus permission to delete
+ littleHTML += '';
+ }
+ littleHTML += '
';
+
+ var render = _.template(littleHTML);
+ var map;
+ Metamaps.Active.Map ? map = Metamaps.Active.Topic.id : map = null;
+ return render({
+ id: node.id,
+ mapid: map,
+ name: node.name
+ });
+ }, // generateLittleHTML
+ renderMidArrow: function (from, to, dim, swap, canvas, placement, newSynapse) {
+ var ctx = canvas.getCtx();
+ // invert edge direction
+ if (swap) {
+ var tmp = from;
+ from = to;
+ to = tmp;
+ }
+ // vect represents a line from tip to tail of the arrow
+ var vect = new $jit.Complex(to.x - from.x, to.y - from.y);
+ // scale it
+ vect.$scale(dim / vect.norm());
+ // compute the midpoint of the edge line
+ var newX = (to.x - from.x) * placement + from.x;
+ var newY = (to.y - from.y) * placement + from.y;
+ var midPoint = new $jit.Complex(newX, newY);
+
+ // move midpoint by half the "length" of the arrow so the arrow is centered on the midpoint
+ var arrowPoint = new $jit.Complex((vect.x / 0.7) + midPoint.x, (vect.y / 0.7) + midPoint.y);
+ // compute the tail intersection point with the edge line
+ var intermediatePoint = new $jit.Complex(arrowPoint.x - vect.x, arrowPoint.y - vect.y);
+ // vector perpendicular to vect
+ var normal = new $jit.Complex(-vect.y / 2, vect.x / 2);
+ var v1 = intermediatePoint.add(normal);
+ var v2 = intermediatePoint.$add(normal.$scale(-1));
+
+ if (newSynapse) {
+ ctx.strokeStyle = "#222222";
+ ctx.lineWidth = 2;
+ ctx.globalAlpha = 0.4;
+ }
+ ctx.beginPath();
+ ctx.moveTo(from.x, from.y);
+ ctx.lineTo(to.x, to.y);
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.moveTo(v1.x, v1.y);
+ ctx.lineTo(arrowPoint.x, arrowPoint.y);
+ ctx.lineTo(v2.x, v2.y);
+ ctx.stroke();
+ }, // renderMidArrow
+ renderEdgeArrows: function (edgeHelper, adj, synapse) {
+
+ var self = Metamaps.JIT;
+
+ var canvas = Metamaps.Visualize.mGraph.canvas;
+
+ var directionCat = synapse.get('category');
+ var direction = synapse.getDirection();
+
+ var pos = adj.nodeFrom.pos.getc(true);
+ var posChild = adj.nodeTo.pos.getc(true);
+
+ //plot arrow edge
+ if (directionCat == "none") {
+ edgeHelper.line.render({
+ x: pos.x,
+ y: pos.y
+ }, {
+ x: posChild.x,
+ y: posChild.y
+ }, canvas);
+ } else if (directionCat == "both") {
+ self.renderMidArrow({
+ x: pos.x,
+ y: pos.y
+ }, {
+ x: posChild.x,
+ y: posChild.y
+ }, 13, true, canvas, 0.7);
+ self.renderMidArrow({
+ x: pos.x,
+ y: pos.y
+ }, {
+ x: posChild.x,
+ y: posChild.y
+ }, 13, false, canvas, 0.7);
+ } else if (directionCat == "from-to") {
+ var direction = adj.data.$direction;
+ var inv = (direction && direction.length > 1 && direction[0] != adj.nodeFrom.id);
+ self.renderMidArrow({
+ x: pos.x,
+ y: pos.y
+ }, {
+ x: posChild.x,
+ y: posChild.y
+ }, 13, inv, canvas, 0.7);
+ self.renderMidArrow({
+ x: pos.x,
+ y: pos.y
+ }, {
+ x: posChild.x,
+ y: posChild.y
+ }, 13, inv, canvas, 0.3);
+ }
+ } //renderEdgeArrows
+};
+Metamaps.Listeners = {
+
+ init: function () {
+
+ $(document).on('keydown', function (e) {
+ switch (e.which) {
+ case 13:
+ Metamaps.JIT.enterKeyHandler();
+ e.preventDefault();
+ break;
+ case 27:
+ Metamaps.JIT.escKeyHandler();
+ break;
+ default:
+ break; //alert(e.which);
+ }
+ });
+
+ //$(window).resize(function () {
+ // Metamaps.Visualize.mGraph.canvas.resize($(window).width(), $(window).height());
+ //});
+ }
+};
+
+Metamaps.Map = {
+ // this function is to retrieve a map JSON object from the database
+ // @param id = the id of the map to retrieve
+ get: function (id, callback) {
+ // if the desired topic is not yet in the local topic repository, fetch it
+ if (Metamaps.Maps.get(id) == undefined) {
+ if (!callback) {
+ var e = $.ajax({
+ url: "/maps/" + id + ".json",
+ async: false
+ });
+ Metamaps.Maps.add($.parseJSON(e.responseText));
+ return Metamaps.Maps.get(id);
+ } else {
+ return $.ajax({
+ url: "/users/" + id + ".json",
+ success: function (data) {
+ Metamaps.Maps.add(data);
+ callback(Metamaps.Maps.get(id));
+ }
+ });
+ }
+ } else {
+ if (!callback) {
+ return Metamaps.Maps.get(id);
+ } else {
+ return callback(Metamaps.Maps.get(id));
+ }
+ }
+ },
+};
+Metamaps.Maps = null; // will be initialized in Metamaps.Backbone.init as a MapCollection
+
+Metamaps.Mapper = {
+ // this function is to retrieve a mapper JSON object from the database
+ // @param id = the id of the mapper to retrieve
+ get: function (id, callback) {
+ // if the desired topic is not yet in the local topic repository, fetch it
+ if (Metamaps.Mappers.get(id) == undefined) {
+ if (!callback) {
+ var e = $.ajax({
+ url: "/users/" + id + ".json",
+ async: false
+ });
+ Metamaps.Mappers.add($.parseJSON(e.responseText));
+ return Metamaps.Mappers.get(id);
+ } else {
+ return $.ajax({
+ url: "/users/" + id + ".json",
+ success: function (data) {
+ Metamaps.Mappers.add(data);
+ callback(Metamaps.Mappers.get(id));
+ }
+ });
+ }
+ } else {
+ if (!callback) {
+ return Metamaps.Mappers.get(id);
+ } else {
+ return callback(Metamaps.Mappers.get(id));
+ }
+ }
+ },
+};
+Metamaps.Mappers = null; // will be initialized in Metamaps.Backbone.init as a MapperCollection
+
+Metamaps.Mouse = {
+ didPan: false,
+ changeInX: 0,
+ changeInY: 0,
+ edgeHoveringOver: false,
+ boxStartCoordinates: false,
+ boxEndCoordinates: false,
+ synapseStartCoordinates: [],
+ synapseEndCoordinates: null,
+ lastNodeClick: 0,
+ lastCanvasClick: 0,
+ DOUBLE_CLICK_TOLERANCE: 300
+};
+Metamaps.Organize = {
+ init: function () {
+
+ },
+ arrange: function (layout, centerNode) {
+ console.log(centerNode);
+ // first option for layout to implement is 'grid', will do an evenly spaced grid with its center at the 0,0 origin
+ if (layout == 'grid') {
+ var numNodes = _.size(Metamaps.Visualize.mGraph.graph.nodes); // this will always be an integer, the # of nodes on your graph visualization
+ var numColumns = Math.floor(Math.sqrt(numNodes)); // the number of columns to make an even grid
+ var GRIDSPACE = 400;
+ var row = 0;
+ var column = 0;
+ Metamaps.Visualize.mGraph.graph.eachNode(function (n) {
+ if (column == numColumns) {
+ column = 0;
+ row += 1;
+ }
+ var newPos = new $jit.Complex();
+ newPos.x = column * GRIDSPACE;
+ newPos.y = row * GRIDSPACE;
+ n.setPos(newPos, 'end');
+ column += 1;
+ });
+ Metamaps.Visualize.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);
+ } else if (layout == 'grid_full') {
+ var numNodes = _.size(Metamaps.Visualize.mGraph.graph.nodes); // this will always be an integer, the # of nodes on your graph visualization
+ //var numColumns = Math.floor(Math.sqrt(numNodes)); // the number of columns to make an even grid
+ //var GRIDSPACE = 400;
+ var height = Metamaps.Visualize.mGraph.canvas.getSize(0).height;
+ var width = Metamaps.Visualize.mGraph.canvas.getSize(0).width;
+ var totalArea = height * width;
+ var cellArea = totalArea / numNodes;
+ var ratio = height / width;
+ var cellWidth = sqrt(cellArea / ratio);
+ var cellHeight = cellArea / cellWidth;
+ var row = floor(height / cellHeight);
+ var column = floor(width / cellWidth);
+ var totalCells = row * column;
+
+ if (totalCells)
+
+
+
+ Metamaps.Visualize.mGraph.graph.eachNode(function (n) {
+ if (column == numColumns) {
+ column = 0;
+ row += 1;
+ }
+ var newPos = new $jit.Complex();
+ newPos.x = column * GRIDSPACE;
+ newPos.y = row * GRIDSPACE;
+ n.setPos(newPos, 'end');
+ column += 1;
+ });
+ Metamaps.Visualize.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);
+ } else if (layout == 'radial') {
+
+ var centerX = centerNode.getPos().x;
+ var centerY = centerNode.getPos().y;
+ centerNode.setPos(centerNode.getPos(), 'end');
+
+ console.log(centerNode.adjacencies);
+ var lineLength = 200;
+ /*
+ centerNode.eachAdjacency(function(n) {
+ var newPos = new $jit.Complex();
+ newPos.x = lineLength*Math.sin(degree) +centerX;
+ newPos.y = lineLength*Math.cos(degree) +centerY;
+ n.nodeTo.setPos(newPos, 'end');
+ degree += angle;
+ });
+ Metamaps.Visualize.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);
+ */
+
+
+
+
+
+ var usedNodes = {};
+ usedNodes[centerNode.id] = centerNode;
+ var radial = function (node, level, degree) {
+ if (level == 1) {
+ var numLinksTemp = _.size(node.adjacencies);
+ var angleTemp = 2 * Math.PI / numLinksTemp;
+ } else {
+ angleTemp = 2 * Math.PI / 20
+ };
+ node.eachAdjacency(function (a) {
+ var isSecondLevelNode = (centerNode.adjacencies[a.nodeTo.id] != undefined && level > 1);
+ if (usedNodes[a.nodeTo.id] == undefined && !isSecondLevelNode) {
+ var newPos = new $jit.Complex();
+ newPos.x = level * lineLength * Math.sin(degree) + centerX;
+ newPos.y = level * lineLength * Math.cos(degree) + centerY;
+ a.nodeTo.setPos(newPos, 'end');
+ usedNodes[a.nodeTo.id] = a.nodeTo;
+
+ radial(a.nodeTo, level + 1, degree);
+ degree += angleTemp;
+ };
+ });
+ };
+ radial(centerNode, 1, 0);
+ Metamaps.Visualize.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);
+
+
+
+
+
+ /*
+ var radial = function (input) {
+ if (column == numColumns) {
+ column = 0;
+ row += 1;
+ }
+ var newPos = new $jit.Complex();
+ newPos.x = column*GRIDSPACE;
+ newPos.y = row*GRIDSPACE;
+ n.setPos(newPos, 'end');
+
+ });
+ Metamaps.Visualize.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);*/
+ } else if (layout == 'center_viewport') {
+
+ var lowX = 0,
+ lowY = 0,
+ highX = 0,
+ highY = 0;
+ var oldOriginX = Metamaps.Visualize.mGraph.canvas.translateOffsetX;
+ var oldOriginY = Metamaps.Visualize.mGraph.canvas.translateOffsetY;
+
+ Metamaps.Visualize.mGraph.graph.eachNode(function (n) {
+ if (n.id === 1) {
+ lowX = n.getPos().x;
+ lowY = n.getPos().y;
+ highX = n.getPos().x;
+ highY = n.getPos().y;
+ };
+
+ if (n.getPos().x < lowX) lowX = n.getPos().x;
+ if (n.getPos().y < lowY) lowY = n.getPos().y;
+ if (n.getPos().x > highX) highX = n.getPos().x;
+ if (n.getPos().y > highY) highY = n.getPos().y;
+
+
+ });
+ console.log(lowX, lowY, highX, highY);
+ var newOriginX = (lowX + highX) / 2;
+ var newOriginY = (lowY + highY) / 2;
+ console.log("new offset: (before translate)", Metamaps.Visualize.mGraph.canvas.translateOffsetX, Metamaps.Visualize.mGraph.canvas.translateOffsetY);
+ console.log("new offset: (before translate)", Metamaps.Visualize.mGraph.canvas.translateOffsetX, Metamaps.Visualize.mGraph.canvas.translateOffsetY);
+ Metamaps.Visualize.mGraph.canvas.translate(newOriginX - oldOriginX, newOriginY - oldOriginY);
+ console.log("ideal offset: ", newOriginX, newOriginY);
+ console.log("new offset: ", Metamaps.Visualize.mGraph.canvas.translateOffsetX, Metamaps.Visualize.mGraph.canvas.translateOffsetY);
+ console.log("new offset: ", Metamaps.Visualize.mGraph.canvas.translateOffsetX, Metamaps.Visualize.mGraph.canvas.translateOffsetY);
+
+
+
+
+
+
+ } else alert('please call function with a valid layout dammit!');
+ },
+ loadSavedLayout: function (id) {
+ Metamaps.Visualize.computePositions();
+ Metamaps.Visualize.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);
+ },
+ saveNewLayout: function () {
+ var layoutName = prompt("Enter a name for your layout...");
+ if (layoutName === null) return;
+ var layoutObject = {};
+ Metamaps.Visualize.mGraph.graph.eachNode(function (n) {
+ layoutObject[n.data.$id] = {
+ x: n.getPos().x,
+ y: n.getPos().y
+ };
+ });
+
+ function addMetadata(e) {
+ // add the 'expressed In English' field
+ Metamaps.Field.createFieldInDatabase("topic", e.id, 1, layoutName);
+ // add the 'is a' synapses
+ Metamaps.Synapse.createSynapseInDatabase(e.id, 2, 1087, false);
+ // add the 'saved coordinates' field
+ Metamaps.Field.createFieldInDatabase("topic", e.id, 1088, JSON.stringify(layoutObject));
+ // add the 'is layout for' synapses
+ Metamaps.Synapse.createSynapseInDatabase(e.id, 1089, Metamaps.Active.Topic.id, false);
+ $('#saveLayout').text('Saved!');
+ setTimeout(function () {
+ $('#saveLayout').text('Save New Layout')
+ }, 1500);
+ Metamaps.Topic.get(e.id, function (ee) {
+ // add the new layout to the list
+ $('#selectSavedLayout').append(Metamaps.Util.generateOptionsList([ee]));
+ // switch to the new layout
+ $('#selectSavedLayout').val(ee.id);
+ });
+ }
+ // call create topic which will run 'addMetadata' when it works
+ Metamaps.Topic.createTopicInDatabase(addMetadata, []);
+ },
+ saveCurrentLayout: function () {
+ var id = $('#selectSavedLayout option:selected').val();
+ if (id != "") {
+ Metamaps.Topic.get(id, function (e) {
+ // this is where the actual saved coordinates are
+ var fieldID = e[1088][2][0];
+ var layoutObject = {};
+ Metamaps.Visualize.mGraph.graph.eachNode(function (n) {
+ layoutObject[n.data.$id] = {
+ x: n.getPos().x,
+ y: n.getPos().y
+ };
+ });
+ // update the 'saved coordinates' field
+ Metamaps.Field.updateFieldInDatabase(fieldID, JSON.stringify(layoutObject));
+ Metamaps.Topic.refresh(e.id);
+ $('#updateLayout').text('Updated!');
+ setTimeout(function () {
+ $('#updateLayout').text('Overwrite Layout')
+ }, 1500);
+ });
+ }
+ }
+};
+
+
+Metamaps.Selected = {
+ Topics: [],
+ Synapses: []
+};
+
+
+Metamaps.Synapse = {
+ // this function is to retrieve a synapse JSON object from the database
+ // @param id = the id of the synapse to retrieve
+ get: function (id, callback) {
+ // if the desired topic is not yet in the local topic repository, fetch it
+ if (Metamaps.Synapses.get(id) == undefined) {
+ if (!callback) {
+ var e = $.ajax({
+ url: "/synapses/" + id + ".json",
+ async: false
+ });
+ Metamaps.Synapses.add($.parseJSON(e.responseText));
+ return Metamaps.Synapses.get(id);
+ } else {
+ return $.ajax({
+ url: "/synapses/" + id + ".json",
+ success: function (data) {
+ Metamaps.Synapses.add(data);
+ callback(Metamaps.Synapses.get(id));
+ }
+ });
+ }
+ } else {
+ if (!callback) {
+ return Metamaps.Synapses.get(id);
+ } else {
+ return callback(Metamaps.Synapses.get(id));
+ }
+ }
+ },
+ /*
+ *
+ *
+ */
+ renderSynapse: function (mapping, synapse, node1, node2, createNewInDB) {
+ var self = Metamaps.Synapse;
+
+ var edgeOnViz;
+
+ var newedge = mapping.createEdge();
+
+ Metamaps.Visualize.mGraph.graph.addAdjacence(node1, node2, newedge.data);
+ edgeOnViz = Metamaps.Visualize.mGraph.graph.getAdjacence(node1.id, node2.id);
+ mapping.set('edge', edgeOnViz);
+ mapping.updateEdge(); // links the topic and the mapping to the node
+
+ Metamaps.Visualize.mGraph.fx.plotLine(edgeOnViz, Metamaps.Visualize.mGraph.canvas);
+ Metamaps.Control.selectEdge(edgeOnViz);
+
+ if (!Metamaps.Settings.sandbox && createNewInDB) {
+ if (synapse.isNew()) {
+ synapse.save(null, {
+ success: function (synapseModel, response) {
+ synapseModel.updateMappings();
+ if (Metamaps.Active.Map) {
+ mapping.save();
+ }
+ },
+ error: function (model, response) {
+ console.log('error saving synapse to database');
+ }
+ });
+ } else if (!synapse.isNew() && Metamaps.Active.Map) {
+ mapping.save();
+ }
+ }
+ },
+ createSynapseLocally: function () {
+ var self = Metamaps.Synapse,
+ topic1,
+ topic2,
+ node1,
+ node2,
+ synapse,
+ mapping;
+
+ //for each node in this array we will create a synapse going to the position2 node.
+ var synapsesToCreate = [];
+
+ node2 = Metamaps.Visualize.mGraph.graph.getNode(Metamaps.Create.newSynapse.topic2id);
+ topic2 = node2.getData('topic');
+
+ var len = Metamaps.Selected.Topics.length;
+ if (len == 0) {
+ synapsesToCreate[0] = Metamaps.Visualize.mGraph.graph.getNode(Metamaps.Create.newSynapse.topic1id);
+ } else if (len > 0) {
+ synapsesToCreate = Metamaps.Selected.Topics;
+ }
+
+ for (var i = 0; i < synapsesToCreate.length; i++) {
+ node1 = synapsesToCreate[i];
+ topic1 = node1.getData('topic');
+ synapse = new Metamaps.Backbone.Synapse({
+ desc: Metamaps.Create.newSynapse.description,
+ node1_id: topic1.isNew() ? topic1.cid : topic1.id,
+ node2_id: topic2.isNew() ? topic2.cid : topic2.id,
+ });
+ Metamaps.Synapses.add(synapse);
+
+ mapping = new Metamaps.Backbone.Mapping({
+ category: "Synapse",
+ synapse_id: synapse.cid
+ });
+ Metamaps.Mappings.add(mapping);
+
+ // this function also includes the creation of the synapse in the database
+ self.renderSynapse(mapping, synapse, node1, node2, true);
+ } // for each in synapsesToCreate
+
+ Metamaps.Create.newSynapse.hide();
+ },
+ getSynapseFromAutocomplete: function (id) {
+ var self = Metamaps.Synapse;
+
+ Metamaps.Create.newSynapse.hide();
+
+ var synapse = self.get(id);
+
+ var mapping = new Metamaps.Backbone.Mapping({
+ category: "Synapse",
+ synapse_id: synapse.id
+ });
+ Metamaps.Mappings.add(mapping);
+
+ self.renderSynapse(mapping, synapse, false);
+ }
+};
+
+
+Metamaps.Synapses = {};
+
+
+Metamaps.SynapseCard = {
+ openSynapseCard: null
+};
+
+
+Metamaps.Touch = {
+ touchPos: null, // this stores the x and y values of a current touch event
+ touchDragNode: null // this stores a reference to a JIT node that is being dragged
+};
+
+
+Metamaps.Util = {
+ // helper function to determine how many lines are needed
+ // Line Splitter Function
+ // copyright Stephen Chapman, 19th April 2006
+ // you may copy this code but please keep the copyright notice as well
+ splitLine: function (st, n) {
+ var b = '';
+ var s = st;
+ while (s.length > n) {
+ var c = s.substring(0, n);
+ var d = c.lastIndexOf(' ');
+ var e = c.lastIndexOf('\n');
+ if (e != -1) d = e;
+ if (d == -1) d = n;
+ b += c.substring(0, d) + '\n';
+ s = s.substring(d + 1);
+ }
+ return b + s;
+ },
+ decodeEntities: function (desc) {
+ var str, temp = document.createElement('p');
+ temp.innerHTML = desc; //browser handles the topics
+ str = temp.textContent || temp.innerText;
+ temp = null; //delete the element;
+ return str;
+ }, //decodeEntities
+ getDistance: function (p1, p2) {
+ return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));
+ },
+ generateOptionsList: function (data) {
+ var newlist = "";
+ for (var i = 0; i < data.length; i++) {
+ newlist = newlist + '';
+ }
+ return newlist;
+ },
+ checkURLisImage: function (url) {
+ // when the page reloads the following regular expression will be screwed up
+ // please replace it with this one before you save: /*backslashhere*.(jpeg|jpg|gif|png)$/
+ return (url.match(/\.(jpeg|jpg|gif|png)$/) != null);
+ },
+ checkURLisYoutubeVideo: function (url) {
+ return (url.match(/^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$/) != null);
+ }
+};
+Metamaps.Visualize = {
+ mGraph: {}, // a reference to the graph object.
+ cameraPosition: null, // stores the camera position when using a 3D visualization
+ type: "ForceDirected", // the type of graph we're building, could be "RGraph", "ForceDirected", or "ForceDirected3D"
+ savedLayout: true, // indicates whether the map has a saved layout or not
+ loadLater: false, // indicates whether there is JSON that should be loaded right in the offset, or whether to wait till the first topic is created
+ target: null, // the selector representing the location to render the graph
+ init: function () {
+ var self = Metamaps.Visualize;
+ // disable awkward dragging of the canvas element that would sometimes happen
+ $('#infovis-canvas').on('dragstart', function (event) {
+ event.preventDefault();
+ });
+
+ // prevent touch events on the canvas from default behaviour
+ $("#infovis-canvas").bind('touchstart', function (event) {
+ event.preventDefault();
+ self.mGraph.events.touched = true;
+ });
+
+ // prevent touch events on the canvas from default behaviour
+ $("#infovis-canvas").bind('touchmove', function (event) {
+ //Metamaps.JIT.touchPanZoomHandler(event);
+ });
+
+ // prevent touch events on the canvas from default behaviour
+ $("#infovis-canvas").bind('touchend touchcancel', function (event) {
+ lastDist = 0;
+ if (!self.mGraph.events.touchMoved && !Metamaps.Touch.touchDragNode) Metamaps.TopicCard.hideCurrentCard();
+ self.mGraph.events.touched = self.mGraph.events.touchMoved = false;
+ Metamaps.Touch.touchDragNode = false;
+ });
+ },
+ render: function (targetID, vizData) {
+ var self = Metamaps.Visualize;
+ self.mGraph = {};
+ self.target = targetID;
+ self.__buildGraph(vizData);
+ },
+ computePositions: function () {
+ var self = Metamaps.Visualize;
+ if (self.type == "RGraph") {
+ self.mGraph.graph.eachNode(function (n) {
+ var pos = n.getPos();
+ pos.setc(-200, -200);
+ });
+ self.mGraph.compute('end');
+ } else if (self.type == "ForceDirected" && self.savedLayout) {
+ var startPos, endPos, mapping;
+
+ self.mGraph.graph.eachNode(function (n) {
+ mapping = Metamaps.Mappings.get(n.id);
+ mapping.set('node', n);
+ mapping.updateNode();
+
+ startPos = new $jit.Complex(0, 0);
+ endPos = new $jit.Complex(mapping.get('xloc'), mapping.get('yloc'));
+ n.setPos(startPos, 'start');
+ n.setPos(endPos, 'end');
+ });
+ } else if (self.type == "ForceDirected3D" || !self.savedLayout) {
+ self.mGraph.compute();
+ }
+ },
+ /**
+ * __buildGraph does the heavy lifting of creating the engine that renders the graph with the properties we desire
+ *
+ * @param vizData a json structure containing the data to be rendered.
+ */
+ __buildGraph: function (vizData) {
+ var self = Metamaps.Visualize;
+
+ // normally this will be true, and will enter into this first scenario
+ if (!Metamaps.Settings.embed) {
+ if (self.type == "RGraph") {
+ $jit.RGraph.Plot.NodeTypes.implement(Metamaps.JIT.RGraph.nodeSettings);
+ $jit.RGraph.Plot.EdgeTypes.implement(Metamaps.JIT.RGraph.edgeSettings);
+ self.mGraph = new $jit.RGraph(Metamaps.JIT.RGraph.graphSettings);
+ } else if (self.type == "ForceDirected") {
+ $jit.ForceDirected.Plot.NodeTypes.implement(Metamaps.JIT.ForceDirected.nodeSettings);
+ $jit.ForceDirected.Plot.EdgeTypes.implement(Metamaps.JIT.ForceDirected.edgeSettings);
+ self.mGraph = new $jit.ForceDirected(Metamaps.JIT.ForceDirected.graphSettings);
+ } else if (self.type == "ForceDirected3D") {
+ // init ForceDirected3D
+ self.mGraph = new $jit.ForceDirected3D(Metamaps.JIT.ForceDirected3D.graphSettings);
+ self.cameraPosition = self.mGraph.canvas.canvases[0].camera.position;
+ }
+ } else { // in the case where these visualizations are to be embedded in other sites TODO
+ if (self.type == "RGraph") {
+ $jit.RGraph.Plot.NodeTypes.implement(Metamaps.JIT.RGraph.embed.nodeSettings);
+ $jit.RGraph.Plot.EdgeTypes.implement(Metamaps.JIT.RGraph.embed.edgeSettings);
+ self.mGraph = new $jit.RGraph(Metamaps.JIT.RGraph.embed.graphSettings);
+ } else if (self.type == "ForceDirected") {
+ $jit.ForceDirected.Plot.NodeTypes.implement(Metamaps.JIT.ForceDirected.embed.nodeSettings);
+ $jit.ForceDirected.Plot.EdgeTypes.implement(Metamaps.JIT.ForceDirected.embed.edgeSettings);
+ self.mGraph = new $jit.ForceDirected(Metamaps.JIT.ForceDirected.embed.graphSettings);
+ } else if (self.type == "ForceDirected3D") {
+ // init ForceDirected3D
+ self.mGraph = new $jit.ForceDirected3D(Metamaps.JIT.ForceDirected3D.embed.graphSettings);
+ self.cameraPosition = self.mGraph.canvas.canvases[0].camera.position;
+ }
+ }
+
+ // load JSON data, if it's not empty
+ if (!self.loadLater) {
+ //load JSON data.
+ self.mGraph.loadJSON(vizData);
+ //compute positions and plot.
+ self.computePositions();
+ if (self.type == "RGraph") {
+ self.mGraph.fx.animate(Metamaps.JIT.RGraph.animate);
+ } else if (self.type == "ForceDirected" && self.savedLayout) {
+ return Metamaps.Organize.loadSavedLayout();
+ //self.mGraph.animate(Metamaps.JIT.ForceDirected.animateSavedLayout);
+ } else if (self.type == "ForceDirected3D" || !self.savedLayout) {
+ self.mGraph.animate(Metamaps.JIT.ForceDirected.animateFDLayout);
+ }
+ }
+ }
+};
+
+
+Metamaps.Realtime = {
+ // this is for the heroku staging environment
+ //Metamaps.Realtime.socket = io.connect('http://gentle-savannah-1303.herokuapp.com');
+ // this is for metamaps.cc
+ //Metamaps.Realtime.socket = io.connect('http://metamaps.cc:5001');
+ // this is for localhost development
+ //Metamaps.Realtime.socket = io.connect('http://localhost:5001');
+ socket: null,
+ notifyTimeOut: null,
+ init: function () {
+ var mapperm = Metamaps.Active.Map.authorizeToEdit(Metamaps.Active.Mapper);
+
+ if (mapperm) {
+ Metamaps.Realtime.socket = io.connect('http://localhost:5001');
+ Metamaps.Realtime.socket.on('connect', function () {
+ console.log('socket connected');
+ Metamaps.Realtime.setupSocket();
+ });
+ }
+ },
+ notifyUser: function (message) {
+ if ($('.notice.metamaps').length == 0) {
+ $('body').prepend('');
+ }
+ $('.notice.metamaps').hide().html(message).fadeIn('fast');
+
+ clearTimeout(Metamaps.Realtime.notifyTimeOut);
+ Metamaps.Realtime.notifyTimeOut = setTimeout(function () {
+ $('.notice.metamaps').fadeOut('fast');
+ }, 8000);
+ },
+ setupSocket: function () {
+ var socket = Metamaps.Realtime.socket;
+
+ socket.emit('newMapperNotify', {
+ userid: userid,
+ username: username,
+ mapid: Metamaps.Active.Map.id
+ });
+
+ // if you're the 'new guy' update your list with who's already online
+ socket.on(userid + '-' + Metamaps.Active.Map.id + '-UpdateMapperList', function (data) {
+ // data.userid
+ // data.username
+ // data.userrealtime
+
+ MetamapsModel.mappersOnMap[data.userid] = {
+ name: data.username,
+ realtime: data.userrealtime
+ };
+
+ var onOff = data.userrealtime ? "On" : "Off";
+ var mapperListItem = '
' + data.username + '
';
+ $('#mapper' + data.userid).remove();
+ $('.realtimeMapperList ul').append(mapperListItem);
+ });
+
+ // receive word that there's a new mapper on the map
+ socket.on('maps-' + Metamaps.Active.Map.id + '-newmapper', function (data) {
+ // data.userid
+ // data.username
+
+ MetamapsModel.mappersOnMap[data.userid] = {
+ name: data.username,
+ realtime: false
+ };
+
+ var mapperListItem = '
' + data.username + '
';
+ $('#mapper' + data.userid).remove();
+ $('.realtimeMapperList ul').append(mapperListItem);
+
+ Metamaps.Realtime.notifyUser(data.username + ' just joined the map');
+
+ // send this new mapper back your details, and the awareness that you've loaded the map
+ var update = {
+ userToNotify: data.userid,
+ username: username,
+ userid: userid,
+ userrealtime: goRealtime,
+ mapid: Metamaps.Active.Map.id
+ };
+ socket.emit('updateNewMapperList', update);
+ });
+
+ // receive word that a mapper left the map
+ socket.on('maps-' + Metamaps.Active.Map.id + '-lostmapper', function (data) {
+ // data.userid
+ // data.username
+
+ delete MetamapsModel.mappersOnMap[data.userid];
+
+ $('#mapper' + data.userid).remove();
+
+ Metamaps.Realtime.notifyUser(data.username + ' just left the map');
+ });
+
+ // receive word that there's a mapper turned on realtime
+ socket.on('maps-' + Metamaps.Active.Map.id + '-newrealtime', function (data) {
+ // data.userid
+ // data.username
+
+ MetamapsModel.mappersOnMap[data.userid].realtime = true;
+
+ $('#mapper' + data.userid).removeClass('littleRtOff').addClass('littleRtOn');
+
+ Metamaps.Realtime.notifyUser(data.username + ' just turned on realtime');
+ });
+
+ // receive word that there's a mapper turned on realtime
+ socket.on('maps-' + Metamaps.Active.Map.id + '-lostrealtime', function (data) {
+ // data.userid
+ // data.username
+
+ MetamapsModel.mappersOnMap[data.userid].realtime = false;
+
+ $('#mapper' + data.userid).removeClass('littleRtOn').addClass('littleRtOff');
+
+ Metamaps.Realtime.notifyUser(data.username + ' just turned off realtime');
+ });
+
+ socket.on('maps-' + Metamaps.Active.Map.id, function (data) {
+
+
+
+ //as long as you weren't the origin of the changes, update your map
+ if (data.origin != userid && goRealtime) {
+ if (data.resource == 'Topic') {
+ topic = $.parseJSON(data.obj);
+
+ if (data.action == 'create') {
+ Metamaps.Realtime.addTopicToMap(topic);
+ } else if (data.action == 'update' && Metamaps.Visualize.mGraph.graph.getNode(topic.id) != 'undefined') {
+ Metamaps.Realtime.updateTopicOnMap(topic);
+ } else if (data.action == 'destroy' && Metamaps.Visualize.mGraph.graph.getNode(topic.id) != 'undefined') {
+ hideNode(topic.id)
+ }
+
+ return;
+ } else if (data.resource == 'Synapse') {
+ synapse = $.parseJSON(data.obj);
+
+ if (data.action == 'create') {
+ Metamaps.Realtime.addSynapseToMap(synapse);
+ } else if (data.action == 'update' &&
+ Metamaps.Visualize.mGraph.graph.getAdjacence(synapse.data.$direction['0'], synapse.data.$direction['1']) != 'undefined') {
+ Metamaps.Realtime.updateSynapseOnMap(synapse);
+ } else if (data.action == 'destroy' &&
+ Metamaps.Visualize.mGraph.graph.getAdjacence(synapse.data.$direction['0'], synapse.data.$direction['1']) != 'undefined') {
+ var edge = Metamaps.Visualize.mGraph.graph.getAdjacence(synapse.data.$direction['0'], synapse.data.$direction['1']);
+ hideEdge(edge);
+ }
+
+ return;
+ }
+ }
+ });
+ },
+ sendRealtimeOn: function () {
+ // send this new mapper back your details, and the awareness that you're online
+ var update = {
+ username: username,
+ userid: userid,
+ mapid: Metamaps.Active.Map.id
+ };
+ Metamaps.Realtime.socket.emit('notifyStartRealtime', update);
+ },
+ sendRealtimeOff: function () {
+ // send this new mapper back your details, and the awareness that you're online
+ var update = {
+ username: username,
+ userid: userid,
+ mapid: Metamaps.Active.Map.id
+ };
+ Metamaps.Realtime.socket.emit('notifyStopRealtime', update);
+ },
+ addTopicToMap: function (topic) {
+ var newPos, tempForT;
+ Metamaps.Visualize.mGraph.graph.addNode(topic);
+ tempForT = Metamaps.Visualize.mGraph.graph.getNode(topic.id);
+ tempForT.setData('dim', 1, 'start');
+ tempForT.setData('dim', 25, 'end');
+ newPos = new $jit.Complex();
+ newPos.x = tempForT.data.$xloc;
+ newPos.y = tempForT.data.$yloc;
+ tempForT.setPos(newPos, 'start');
+ tempForT.setPos(newPos, 'current');
+ tempForT.setPos(newPos, 'end');
+ Metamaps.Visualize.mGraph.fx.plotNode(tempForT, Metamaps.Visualize.mGraph.canvas);
+ return Metamaps.Visualize.mGraph.labels.plotLabel(Metamaps.Visualize.mGraph.canvas, tempForT, Metamaps.Visualize.mGraph.config);
+ },
+ updateTopicOnMap: function (topic) {
+ var newPos, tempForT;
+ tempForT = Metamaps.Visualize.mGraph.graph.getNode(topic.id);
+ tempForT.data = topic.data;
+ tempForT.name = topic.name;
+ if (MetamapsModel.showcardInUse === topic.id) {
+ populateShowCard(tempForT);
+ }
+ newPos = new $jit.Complex();
+ newPos.x = tempForT.data.$xloc;
+ newPos.y = tempForT.data.$yloc;
+ tempForT.setPos(newPos, 'start');
+ tempForT.setPos(newPos, 'current');
+ tempForT.setPos(newPos, 'end');
+ return Metamaps.Visualize.mGraph.fx.animate({
+ modes: ['linear', 'node-property:dim', 'edge-property:lineWidth'],
+ transition: $jit.Trans.Quad.easeInOut,
+ duration: 500
+ });
+ },
+ addSynapseToMap: function (synapse) {
+ var Node1, Node2, tempForS;
+ Node1 = Metamaps.Visualize.mGraph.graph.getNode(synapse.data.$direction[0]);
+ Node2 = Metamaps.Visualize.mGraph.graph.getNode(synapse.data.$direction[1]);
+ Metamaps.Visualize.mGraph.graph.addAdjacence(Node1, Node2, {});
+ tempForS = Metamaps.Visualize.mGraph.graph.getAdjacence(Node1.id, Node2.id);
+ tempForS.setDataset('start', {
+ lineWidth: 0.4
+ });
+ tempForS.setDataset('end', {
+ lineWidth: 2
+ });
+ tempForS.data = synapse.data;
+ Metamaps.Visualize.mGraph.fx.plotLine(tempForS, Metamaps.Visualize.mGraph.canvas);
+ return Metamaps.Visualize.mGraph.fx.animate({
+ modes: ['linear', 'node-property:dim', 'edge-property:lineWidth'],
+ transition: $jit.Trans.Quad.easeInOut,
+ duration: 500
+ });
+ },
+ updateSynapseOnMap: function (synapse) {
+ var k, tempForS, v, wasShowDesc, _ref;
+ tempForS = Metamaps.Visualize.mGraph.graph.getAdjacence(synapse.data.$direction[0], synapse.data.$direction[1]);
+ wasShowDesc = tempForS.data.$showDesc;
+ _ref = synapse.data;
+ for (k in _ref) {
+ v = _ref[k];
+ tempForS.data[k] = v;
+ }
+ tempForS.data.$showDesc = wasShowDesc;
+ if (MetamapsModel.edgecardInUse === synapse.data.$id) {
+ editEdge(tempForS, false);
+ }
+ return Metamaps.Visualize.mGraph.plot();
+ }
+};
\ No newline at end of file
diff --git a/app/assets/javascripts/metamaps/metamapsJIT.js b/app/assets/javascripts/metamaps/metamapsJIT.js
new file mode 100644
index 00000000..50b3afcc
--- /dev/null
+++ b/app/assets/javascripts/metamaps/metamapsJIT.js
@@ -0,0 +1,11149 @@
+/*
+Copyright (c) 2011 Sencha Inc. - Author: Nicolas Garcia Belmonte (http://philogb.github.com/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+ */
+ (function () {
+
+/*
+ File: Core.js
+
+ */
+
+/*
+ Object: $jit
+
+ Defines the namespace for all library Classes and Objects.
+ This variable is the *only* global variable defined in the Toolkit.
+ There are also other interesting properties attached to this variable described below.
+ */
+window.$jit = function(w) {
+ w = w || window;
+ for(var k in $jit) {
+ if($jit[k].$extend) {
+ w[k] = $jit[k];
+ }
+ }
+};
+
+$jit.version = '2.0.1';
+/*
+ Object: $jit.id
+
+ Works just like *document.getElementById*
+
+ Example:
+ (start code js)
+ var element = $jit.id('elementId');
+ (end code)
+
+*/
+
+/*
+ Object: $jit.util
+
+ Contains utility functions.
+
+ Some of the utility functions and the Class system were based in the MooTools Framework
+ . Copyright (c) 2006-2010 Valerio Proietti, .
+ MIT license .
+
+ These methods are generally also implemented in DOM manipulation frameworks like JQuery, MooTools and Prototype.
+ I'd suggest you to use the functions from those libraries instead of using these, since their functions
+ are widely used and tested in many different platforms/browsers. Use these functions only if you have to.
+
+ */
+var $ = function(d) {
+ return document.getElementById(d);
+};
+
+$.empty = function() {
+};
+
+/*
+ Method: extend
+
+ Augment an object by appending another object's properties.
+
+ Parameters:
+
+ original - (object) The object to be extended.
+ extended - (object) An object which properties are going to be appended to the original object.
+
+ Example:
+ (start code js)
+ $jit.util.extend({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 4 }); //{ 'a':1, 'b': 3, 'c': 4 }
+ (end code)
+*/
+$.extend = function(original, extended) {
+ for ( var key in (extended || {}))
+ original[key] = extended[key];
+ return original;
+};
+
+$.lambda = function(value) {
+ return (typeof value == 'function') ? value : function() {
+ return value;
+ };
+};
+
+$.time = Date.now || function() {
+ return +new Date;
+};
+
+/*
+ Method: splat
+
+ Returns an array wrapping *obj* if *obj* is not an array. Returns *obj* otherwise.
+
+ Parameters:
+
+ obj - (mixed) The object to be wrapped in an array.
+
+ Example:
+ (start code js)
+ $jit.util.splat(3); //[3]
+ $jit.util.splat([3]); //[3]
+ (end code)
+*/
+$.splat = function(obj) {
+ var type = $.type(obj);
+ return type ? ((type != 'array') ? [ obj ] : obj) : [];
+};
+
+$.type = function(elem) {
+ var type = $.type.s.call(elem).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
+ if(type != 'object') return type;
+ if(elem && elem.$$family) return elem.$$family;
+ return (elem && elem.nodeName && elem.nodeType == 1)? 'element' : type;
+};
+$.type.s = Object.prototype.toString;
+
+/*
+ Method: each
+
+ Iterates through an iterable applying *f*.
+
+ Parameters:
+
+ iterable - (array) The original array.
+ fn - (function) The function to apply to the array elements.
+
+ Example:
+ (start code js)
+ $jit.util.each([3, 4, 5], function(n) { alert('number ' + n); });
+ (end code)
+*/
+$.each = function(iterable, fn) {
+ var type = $.type(iterable);
+ if (type == 'object') {
+ for ( var key in iterable)
+ fn(iterable[key], key);
+ } else {
+ for ( var i = 0, l = iterable.length; i < l; i++)
+ fn(iterable[i], i);
+ }
+};
+
+$.indexOf = function(array, item) {
+ if(Array.indexOf) return array.indexOf(item);
+ for(var i=0,l=array.length; i> 16, hex >> 8 & 0xff, hex & 0xff ];
+ }
+};
+
+$.destroy = function(elem) {
+ $.clean(elem);
+ if (elem.parentNode)
+ elem.parentNode.removeChild(elem);
+ if (elem.clearAttributes)
+ elem.clearAttributes();
+};
+
+$.clean = function(elem) {
+ for (var ch = elem.childNodes, i = 0, l = ch.length; i < l; i++) {
+ $.destroy(ch[i]);
+ }
+};
+
+/*
+ Method: addEvent
+
+ Cross-browser add event listener.
+
+ Parameters:
+
+ obj - (obj) The Element to attach the listener to.
+ type - (string) The listener type. For example 'click', or 'mousemove'.
+ fn - (function) The callback function to be used when the event is fired.
+
+ Example:
+ (start code js)
+ $jit.util.addEvent(elem, 'click', function(){ alert('hello'); });
+ (end code)
+*/
+$.addEvent = function(obj, type, fn) {
+ if (obj.addEventListener)
+ obj.addEventListener(type, fn, false);
+ else
+ obj.attachEvent('on' + type, fn);
+};
+
+$.addEvents = function(obj, typeObj) {
+ for(var type in typeObj) {
+ $.addEvent(obj, type, typeObj[type]);
+ }
+};
+
+$.hasClass = function(obj, klass) {
+ return (' ' + obj.className + ' ').indexOf(' ' + klass + ' ') > -1;
+};
+
+$.addClass = function(obj, klass) {
+ if (!$.hasClass(obj, klass))
+ obj.className = (obj.className + " " + klass);
+};
+
+$.removeClass = function(obj, klass) {
+ obj.className = obj.className.replace(new RegExp(
+ '(^|\\s)' + klass + '(?:\\s|$)'), '$1');
+};
+
+$.getPos = function(elem) {
+ var offset = getOffsets(elem);
+ var scroll = getScrolls(elem);
+ return {
+ x: offset.x - scroll.x,
+ y: offset.y - scroll.y
+ };
+
+ function getOffsets(elem) {
+ var position = {
+ x: 0,
+ y: 0
+ };
+ while (elem && !isBody(elem)) {
+ position.x += elem.offsetLeft;
+ position.y += elem.offsetTop;
+ elem = elem.offsetParent;
+ }
+ return position;
+ }
+
+ function getScrolls(elem) {
+ var position = {
+ x: 0,
+ y: 0
+ };
+ while (elem && !isBody(elem)) {
+ position.x += elem.scrollLeft;
+ position.y += elem.scrollTop;
+ elem = elem.parentNode;
+ }
+ return position;
+ }
+
+ function isBody(element) {
+ return (/^(?:body|html)$/i).test(element.tagName);
+ }
+};
+
+$.event = {
+ get: function(e, win) {
+ win = win || window;
+ return e || win.event;
+ },
+ getWheel: function(e) {
+ return e.wheelDelta? e.wheelDelta / 120 : -(e.detail || 0) / 3;
+ },
+ isRightClick: function(e) {
+ return (e.which == 3 || e.button == 2);
+ },
+ getPos: function(e, win) {
+ // get mouse position
+ win = win || window;
+ e = e || win.event;
+ var doc = win.document;
+ doc = doc.documentElement || doc.body;
+ //TODO(nico): make touch event handling better
+ if(e.touches && e.touches.length) {
+ e = e.touches[0];
+ }
+ var page = {
+ x: e.pageX || (e.clientX + doc.scrollLeft),
+ y: e.pageY || (e.clientY + doc.scrollTop)
+ };
+ return page;
+ },
+ stop: function(e) {
+ if (e.stopPropagation) e.stopPropagation();
+ e.cancelBubble = true;
+ if (e.preventDefault) e.preventDefault();
+ else e.returnValue = false;
+ }
+};
+
+$jit.util = $jit.id = $;
+
+var Class = function(properties) {
+ properties = properties || {};
+ var klass = function() {
+ for ( var key in this) {
+ if (typeof this[key] != 'function')
+ this[key] = $.unlink(this[key]);
+ }
+ this.constructor = klass;
+ if (Class.prototyping)
+ return this;
+ var instance = this.initialize ? this.initialize.apply(this, arguments)
+ : this;
+ //typize
+ this.$$family = 'class';
+ return instance;
+ };
+
+ for ( var mutator in Class.Mutators) {
+ if (!properties[mutator])
+ continue;
+ properties = Class.Mutators[mutator](properties, properties[mutator]);
+ delete properties[mutator];
+ }
+
+ $.extend(klass, this);
+ klass.constructor = Class;
+ klass.prototype = properties;
+ return klass;
+};
+
+Class.Mutators = {
+
+ Implements: function(self, klasses) {
+ $.each($.splat(klasses), function(klass) {
+ Class.prototyping = klass;
+ var instance = (typeof klass == 'function') ? new klass : klass;
+ for ( var prop in instance) {
+ if (!(prop in self)) {
+ self[prop] = instance[prop];
+ }
+ }
+ delete Class.prototyping;
+ });
+ return self;
+ }
+
+};
+
+$.extend(Class, {
+
+ inherit: function(object, properties) {
+ for ( var key in properties) {
+ var override = properties[key];
+ var previous = object[key];
+ var type = $.type(override);
+ if (previous && type == 'function') {
+ if (override != previous) {
+ Class.override(object, key, override);
+ }
+ } else if (type == 'object') {
+ object[key] = $.merge(previous, override);
+ } else {
+ object[key] = override;
+ }
+ }
+ return object;
+ },
+
+ override: function(object, name, method) {
+ var parent = Class.prototyping;
+ if (parent && object[name] != parent[name])
+ parent = null;
+ var override = function() {
+ var previous = this.parent;
+ this.parent = parent ? parent[name] : object[name];
+ var value = method.apply(this, arguments);
+ this.parent = previous;
+ return value;
+ };
+ object[name] = override;
+ }
+
+});
+
+Class.prototype.implement = function() {
+ var proto = this.prototype;
+ $.each(Array.prototype.slice.call(arguments || []), function(properties) {
+ Class.inherit(proto, properties);
+ });
+ return this;
+};
+
+$jit.Class = Class;
+
+/*
+ Object: $jit.json
+
+ Provides JSON utility functions.
+
+ Most of these functions are JSON-tree traversal and manipulation functions.
+*/
+$jit.json = {
+ /*
+ Method: prune
+
+ Clears all tree nodes having depth greater than maxLevel.
+
+ Parameters:
+
+ tree - (object) A JSON tree object. For more information please see .
+ maxLevel - (number) An integer specifying the maximum level allowed for this tree. All nodes having depth greater than max level will be deleted.
+
+ */
+ prune: function(tree, maxLevel) {
+ this.each(tree, function(elem, i) {
+ if (i == maxLevel && elem.children) {
+ delete elem.children;
+ elem.children = [];
+ }
+ });
+ },
+ /*
+ Method: getParent
+
+ Returns the parent node of the node having _id_ as id.
+
+ Parameters:
+
+ tree - (object) A JSON tree object. See also .
+ id - (string) The _id_ of the child node whose parent will be returned.
+
+ Returns:
+
+ A tree JSON node if any, or false otherwise.
+
+ */
+ getParent: function(tree, id) {
+ if (tree.id == id)
+ return false;
+ var ch = tree.children;
+ if (ch && ch.length > 0) {
+ for ( var i = 0; i < ch.length; i++) {
+ if (ch[i].id == id)
+ return tree;
+ else {
+ var ans = this.getParent(ch[i], id);
+ if (ans)
+ return ans;
+ }
+ }
+ }
+ return false;
+ },
+ /*
+ Method: getSubtree
+
+ Returns the subtree that matches the given id.
+
+ Parameters:
+
+ tree - (object) A JSON tree object. See also .
+ id - (string) A node *unique* identifier.
+
+ Returns:
+
+ A subtree having a root node matching the given id. Returns null if no subtree matching the id is found.
+
+ */
+ getSubtree: function(tree, id) {
+ if (tree.id == id)
+ return tree;
+ for ( var i = 0, ch = tree.children; ch && i < ch.length; i++) {
+ var t = this.getSubtree(ch[i], id);
+ if (t != null)
+ return t;
+ }
+ return null;
+ },
+ /*
+ Method: eachLevel
+
+ Iterates on tree nodes with relative depth less or equal than a specified level.
+
+ Parameters:
+
+ tree - (object) A JSON tree or subtree. See also .
+ initLevel - (number) An integer specifying the initial relative level. Usually zero.
+ toLevel - (number) An integer specifying a top level. This method will iterate only through nodes with depth less than or equal this number.
+ action - (function) A function that receives a node and an integer specifying the actual level of the node.
+
+ Example:
+ (start code js)
+ $jit.json.eachLevel(tree, 0, 3, function(node, depth) {
+ alert(node.name + ' ' + depth);
+ });
+ (end code)
+ */
+ eachLevel: function(tree, initLevel, toLevel, action) {
+ if (initLevel <= toLevel) {
+ action(tree, initLevel);
+ if(!tree.children) return;
+ for ( var i = 0, ch = tree.children; i < ch.length; i++) {
+ this.eachLevel(ch[i], initLevel + 1, toLevel, action);
+ }
+ }
+ },
+ /*
+ Method: each
+
+ A JSON tree iterator.
+
+ Parameters:
+
+ tree - (object) A JSON tree or subtree. See also .
+ action - (function) A function that receives a node.
+
+ Example:
+ (start code js)
+ $jit.json.each(tree, function(node) {
+ alert(node.name);
+ });
+ (end code)
+
+ */
+ each: function(tree, action) {
+ this.eachLevel(tree, 0, Number.MAX_VALUE, action);
+ }
+};
+
+
+/*
+ An object containing multiple type of transformations.
+*/
+
+$jit.Trans = {
+ $extend: true,
+
+ linear: function(p){
+ return p;
+ }
+};
+
+var Trans = $jit.Trans;
+
+(function(){
+
+ var makeTrans = function(transition, params){
+ params = $.splat(params);
+ return $.extend(transition, {
+ easeIn: function(pos){
+ return transition(pos, params);
+ },
+ easeOut: function(pos){
+ return 1 - transition(1 - pos, params);
+ },
+ easeInOut: function(pos){
+ return (pos <= 0.5)? transition(2 * pos, params) / 2 : (2 - transition(
+ 2 * (1 - pos), params)) / 2;
+ }
+ });
+ };
+
+ var transitions = {
+
+ Pow: function(p, x){
+ return Math.pow(p, x[0] || 6);
+ },
+
+ Expo: function(p){
+ return Math.pow(2, 8 * (p - 1));
+ },
+
+ Circ: function(p){
+ return 1 - Math.sin(Math.acos(p));
+ },
+
+ Sine: function(p){
+ return 1 - Math.sin((1 - p) * Math.PI / 2);
+ },
+
+ Back: function(p, x){
+ x = x[0] || 1.618;
+ return Math.pow(p, 2) * ((x + 1) * p - x);
+ },
+
+ Bounce: function(p){
+ var value;
+ for ( var a = 0, b = 1; 1; a += b, b /= 2) {
+ if (p >= (7 - 4 * a) / 11) {
+ value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
+ break;
+ }
+ }
+ return value;
+ },
+
+ Elastic: function(p, x){
+ return Math.pow(2, 10 * --p)
+ * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
+ }
+
+ };
+
+ $.each(transitions, function(val, key){
+ Trans[key] = makeTrans(val);
+ });
+
+ $.each( [
+ 'Quad', 'Cubic', 'Quart', 'Quint'
+ ], function(elem, i){
+ Trans[elem] = makeTrans(function(p){
+ return Math.pow(p, [
+ i + 2
+ ]);
+ });
+ });
+
+})();
+
+/*
+ A Class that can perform animations for generic objects.
+
+ If you are looking for animation transitions please take a look at the object.
+
+ Used by:
+
+
+
+ Based on:
+
+ The Animation class is based in the MooTools Framework . Copyright (c) 2006-2009 Valerio Proietti, . MIT license .
+
+*/
+
+var Animation = new Class( {
+
+ initialize: function(options){
+ this.setOptions(options);
+ },
+
+ setOptions: function(options){
+ var opt = {
+ duration: 2500,
+ fps: 40,
+ transition: Trans.Quart.easeInOut,
+ compute: $.empty,
+ complete: $.empty,
+ link: 'ignore'
+ };
+ this.opt = $.merge(opt, options || {});
+ return this;
+ },
+
+ step: function(){
+ var time = $.time(), opt = this.opt;
+ if (time < this.time + opt.duration) {
+ var delta = opt.transition((time - this.time) / opt.duration);
+ opt.compute(delta);
+ } else {
+ this.timer = clearInterval(this.timer);
+ opt.compute(1);
+ opt.complete();
+ }
+ },
+
+ start: function(){
+ if (!this.check())
+ return this;
+ this.time = 0;
+ this.startTimer();
+ return this;
+ },
+
+ startTimer: function(){
+ var that = this, fps = this.opt.fps;
+ if (this.timer)
+ return false;
+ this.time = $.time() - this.time;
+ this.timer = setInterval((function(){
+ that.step();
+ }), Math.round(1000 / fps));
+ return true;
+ },
+
+ pause: function(){
+ this.stopTimer();
+ return this;
+ },
+
+ resume: function(){
+ this.startTimer();
+ return this;
+ },
+
+ stopTimer: function(){
+ if (!this.timer)
+ return false;
+ this.time = $.time() - this.time;
+ this.timer = clearInterval(this.timer);
+ return true;
+ },
+
+ check: function(){
+ if (!this.timer)
+ return true;
+ if (this.opt.link == 'cancel') {
+ this.stopTimer();
+ return true;
+ }
+ return false;
+ }
+});
+
+
+var Options = function() {
+ var args = arguments;
+ for(var i=0, l=args.length, ans={}; i instance to be used by the visualization.
+ withLabels - (boolean) Default's *true*. Whether to use a label container for the visualization.
+ background - (boolean|object) Default's *false*. An object containing information about the rendering of a background canvas.
+*/
+
+Options.Canvas = {
+ $extend: true,
+
+ injectInto: 'id',
+ type: '2D',
+ width: false,
+ height: false,
+ useCanvas: false,
+ withLabels: true,
+ background: false,
+
+ Scene: {
+ Lighting: {
+ enable: false,
+ ambient: [1, 1, 1],
+ directional: {
+ direction: { x: -100, y: -100, z: -100 },
+ color: [0.5, 0.3, 0.1]
+ }
+ }
+ }
+};
+
+/*
+ * File: Options.Node.js
+ *
+*/
+
+/*
+ Object: Options.Node
+
+ Provides Node rendering options for Tree and Graph based visualizations.
+
+ Syntax:
+
+ (start code js)
+ Options.Node = {
+ overridable: false,
+ type: 'circle',
+ color: '#ccb',
+ alpha: 1,
+ dim: 3,
+ height: 20,
+ width: 90,
+ autoHeight: false,
+ autoWidth: false,
+ lineWidth: 1,
+ transform: true,
+ align: "center",
+ angularWidth:1,
+ span:1,
+ CanvasStyles: {}
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ Node: {
+ overridable: true,
+ width: 30,
+ autoHeight: true,
+ type: 'rectangle'
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ overridable - (boolean) Default's *false*. Determine whether or not general node properties can be overridden by a particular .
+ type - (string) Default's *circle*. Node's shape. Node built-in types include 'circle', 'rectangle', 'square', 'ellipse', 'triangle', 'star'. The default Node type might vary in each visualization. You can also implement (non built-in) custom Node types into your visualizations.
+ color - (string) Default's *#ccb*. Node color.
+ alpha - (number) Default's *1*. The Node's alpha value. *1* is for full opacity.
+ dim - (number) Default's *3*. An extra parameter used by 'circle', 'square', 'triangle' and 'star' node types. Depending on each shape, this parameter can set the radius of a circle, half the length of the side of a square, half the base and half the height of a triangle or the length of a side of a star (concave decagon).
+ height - (number) Default's *20*. Used by 'rectangle' and 'ellipse' node types. The height of the node shape.
+ width - (number) Default's *90*. Used by 'rectangle' and 'ellipse' node types. The width of the node shape.
+ autoHeight - (boolean) Default's *false*. Whether to set an auto height for the node depending on the content of the Node's label.
+ autoWidth - (boolean) Default's *false*. Whether to set an auto width for the node depending on the content of the Node's label.
+ lineWidth - (number) Default's *1*. Used only by some Node shapes. The line width of the strokes of a node.
+ transform - (boolean) Default's *true*. Only used by the visualization. Whether to scale the nodes according to the moebius transformation.
+ align - (string) Default's *center*. Possible values are 'center', 'left' or 'right'. Used only by the visualization, these parameters are used for aligning nodes when some of they dimensions vary.
+ angularWidth - (number) Default's *1*. Used in radial layouts (like or visualizations). The amount of relative 'space' set for a node.
+ span - (number) Default's *1*. Used in radial layouts (like or visualizations). The angle span amount set for a node.
+ CanvasStyles - (object) Default's an empty object (i.e. {}). Attach any other canvas specific property that you'd set to the canvas context before plotting a Node.
+
+*/
+Options.Node = {
+ $extend: false,
+
+ overridable: false,
+ type: 'circle',
+ color: '#ccb',
+ alpha: 1,
+ dim: 3,
+ height: 20,
+ width: 90,
+ autoHeight: false,
+ autoWidth: false,
+ lineWidth: 1,
+ transform: true,
+ align: "center",
+ angularWidth:1,
+ span:1,
+ //Raw canvas styles to be
+ //applied to the context instance
+ //before plotting a node
+ CanvasStyles: {}
+};
+
+
+/*
+ * File: Options.Edge.js
+ *
+*/
+
+/*
+ Object: Options.Edge
+
+ Provides Edge rendering options for Tree and Graph based visualizations.
+
+ Syntax:
+
+ (start code js)
+ Options.Edge = {
+ overridable: false,
+ type: 'line',
+ color: '#ccb',
+ lineWidth: 1,
+ dim:15,
+ alpha: 1,
+ CanvasStyles: {}
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ Edge: {
+ overridable: true,
+ type: 'line',
+ color: '#fff',
+ CanvasStyles: {
+ shadowColor: '#ccc',
+ shadowBlur: 10
+ }
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ overridable - (boolean) Default's *false*. Determine whether or not general edges properties can be overridden by a particular .
+ type - (string) Default's 'line'. Edge styles include 'line', 'hyperline', 'arrow'. The default Edge type might vary in each visualization. You can also implement custom Edge types.
+ color - (string) Default's '#ccb'. Edge color.
+ lineWidth - (number) Default's *1*. Line/Edge width.
+ alpha - (number) Default's *1*. The Edge's alpha value. *1* is for full opacity.
+ dim - (number) Default's *15*. An extra parameter used by other complex shapes such as quadratic, bezier or arrow, to determine the shape's diameter.
+ epsilon - (number) Default's *7*. Only used when using *enableForEdges* in . This dimension is used to create an area for the line where the contains method for the edge returns *true*.
+ CanvasStyles - (object) Default's an empty object (i.e. {}). Attach any other canvas specific property that you'd set to the canvas context before plotting an Edge.
+
+ See also:
+
+ If you want to know more about how to customize Node/Edge data per element, in the JSON or programmatically, take a look at this article.
+*/
+Options.Edge = {
+ $extend: false,
+
+ overridable: false,
+ type: 'line',
+ color: '#ccb',
+ lineWidth: 1,
+ dim:15,
+ alpha: 1,
+ epsilon: 7,
+
+ //Raw canvas styles to be
+ //applied to the context instance
+ //before plotting an edge
+ CanvasStyles: {}
+};
+
+
+/*
+ * File: Options.Fx.js
+ *
+*/
+
+/*
+ Object: Options.Fx
+
+ Provides animation options like duration of the animations, frames per second and animation transitions.
+
+ Syntax:
+
+ (start code js)
+ Options.Fx = {
+ fps:40,
+ duration: 2500,
+ transition: $jit.Trans.Quart.easeInOut,
+ clearCanvas: true
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ duration: 1000,
+ fps: 35,
+ transition: $jit.Trans.linear
+ });
+ (end code)
+
+ Parameters:
+
+ clearCanvas - (boolean) Default's *true*. Whether to clear the frame/canvas when the viz is plotted or animated.
+ duration - (number) Default's *2500*. Duration of the animation in milliseconds.
+ fps - (number) Default's *40*. Frames per second.
+ transition - (object) Default's *$jit.Trans.Quart.easeInOut*. The transition used for the animations. See below for a more detailed explanation.
+
+ Object: $jit.Trans
+
+ This object is used for specifying different animation transitions in all visualizations.
+
+ There are many different type of animation transitions.
+
+ linear:
+
+ Displays a linear transition
+
+ >Trans.linear
+
+ (see Linear.png)
+
+ Quad:
+
+ Displays a Quadratic transition.
+
+ >Trans.Quad.easeIn
+ >Trans.Quad.easeOut
+ >Trans.Quad.easeInOut
+
+ (see Quad.png)
+
+ Cubic:
+
+ Displays a Cubic transition.
+
+ >Trans.Cubic.easeIn
+ >Trans.Cubic.easeOut
+ >Trans.Cubic.easeInOut
+
+ (see Cubic.png)
+
+ Quart:
+
+ Displays a Quartetic transition.
+
+ >Trans.Quart.easeIn
+ >Trans.Quart.easeOut
+ >Trans.Quart.easeInOut
+
+ (see Quart.png)
+
+ Quint:
+
+ Displays a Quintic transition.
+
+ >Trans.Quint.easeIn
+ >Trans.Quint.easeOut
+ >Trans.Quint.easeInOut
+
+ (see Quint.png)
+
+ Expo:
+
+ Displays an Exponential transition.
+
+ >Trans.Expo.easeIn
+ >Trans.Expo.easeOut
+ >Trans.Expo.easeInOut
+
+ (see Expo.png)
+
+ Circ:
+
+ Displays a Circular transition.
+
+ >Trans.Circ.easeIn
+ >Trans.Circ.easeOut
+ >Trans.Circ.easeInOut
+
+ (see Circ.png)
+
+ Sine:
+
+ Displays a Sineousidal transition.
+
+ >Trans.Sine.easeIn
+ >Trans.Sine.easeOut
+ >Trans.Sine.easeInOut
+
+ (see Sine.png)
+
+ Back:
+
+ >Trans.Back.easeIn
+ >Trans.Back.easeOut
+ >Trans.Back.easeInOut
+
+ (see Back.png)
+
+ Bounce:
+
+ Bouncy transition.
+
+ >Trans.Bounce.easeIn
+ >Trans.Bounce.easeOut
+ >Trans.Bounce.easeInOut
+
+ (see Bounce.png)
+
+ Elastic:
+
+ Elastic curve.
+
+ >Trans.Elastic.easeIn
+ >Trans.Elastic.easeOut
+ >Trans.Elastic.easeInOut
+
+ (see Elastic.png)
+
+ Based on:
+
+ Easing and Transition animation methods are based in the MooTools Framework . Copyright (c) 2006-2010 Valerio Proietti, . MIT license .
+
+
+*/
+Options.Fx = {
+ $extend: true,
+
+ fps:40,
+ duration: 2500,
+ transition: $jit.Trans.Quart.easeInOut,
+ clearCanvas: true
+};
+
+/*
+ * File: Options.Label.js
+ *
+*/
+/*
+ Object: Options.Label
+
+ Provides styling for Labels such as font size, family, etc. Also sets Node labels as HTML, SVG or Native canvas elements.
+
+ Syntax:
+
+ (start code js)
+ Options.Label = {
+ overridable: false,
+ type: 'HTML', //'SVG', 'Native'
+ style: ' ',
+ size: 10,
+ family: 'sans-serif',
+ textAlign: 'center',
+ textBaseline: 'alphabetic',
+ color: '#fff'
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ Label: {
+ type: 'Native',
+ size: 11,
+ color: '#ccc'
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ overridable - (boolean) Default's *false*. Determine whether or not general label properties can be overridden by a particular .
+ type - (string) Default's *HTML*. The type for the labels. Can be 'HTML', 'SVG' or 'Native' canvas labels.
+ style - (string) Default's *empty string*. Can be 'italic' or 'bold'. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels.
+ size - (number) Default's *10*. The font's size. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels.
+ family - (string) Default's *sans-serif*. The font's family. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels.
+ color - (string) Default's *#fff*. The font's color. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels.
+*/
+Options.Label = {
+ $extend: false,
+
+ overridable: false,
+ type: 'HTML', //'SVG', 'Native'
+ style: ' ',
+ size: 10,
+ family: 'sans-serif',
+ textAlign: 'center',
+ textBaseline: 'alphabetic',
+ color: '#fff'
+};
+
+
+/*
+ * File: Options.Tips.js
+ *
+ */
+
+/*
+ Object: Options.Tips
+
+ Tips options
+
+ Syntax:
+
+ (start code js)
+ Options.Tips = {
+ enable: false,
+ type: 'auto',
+ offsetX: 20,
+ offsetY: 20,
+ onShow: $.empty,
+ onHide: $.empty
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ Tips: {
+ enable: true,
+ type: 'Native',
+ offsetX: 10,
+ offsetY: 10,
+ onShow: function(tip, node) {
+ tip.innerHTML = node.name;
+ }
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ enable - (boolean) Default's *false*. If *true*, a tooltip will be shown when a node is hovered. The tooltip is a div DOM element having "tip" as CSS class.
+ type - (string) Default's *auto*. Defines where to attach the MouseEnter/Leave tooltip events. Possible values are 'Native' to attach them to the canvas or 'HTML' to attach them to DOM label elements (if defined). 'auto' sets this property to the value of 's *type* property.
+ offsetX - (number) Default's *20*. An offset added to the current tooltip x-position (which is the same as the current mouse position). Default's 20.
+ offsetY - (number) Default's *20*. An offset added to the current tooltip y-position (which is the same as the current mouse position). Default's 20.
+ onShow(tip, node) - This callack is used right before displaying a tooltip. The first formal parameter is the tip itself (which is a DivElement). The second parameter may be a for graph based visualizations or an object with label, value properties for charts.
+ onHide() - This callack is used when hiding a tooltip.
+
+*/
+Options.Tips = {
+ $extend: false,
+
+ enable: false,
+ type: 'auto',
+ offsetX: 20,
+ offsetY: 20,
+ force: false,
+ onShow: $.empty,
+ onHide: $.empty
+};
+
+
+/*
+ * File: Options.NodeStyles.js
+ *
+ */
+
+/*
+ Object: Options.NodeStyles
+
+ Apply different styles when a node is hovered or selected.
+
+ Syntax:
+
+ (start code js)
+ Options.NodeStyles = {
+ enable: false,
+ type: 'auto',
+ stylesHover: false,
+ stylesClick: false
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ NodeStyles: {
+ enable: true,
+ type: 'Native',
+ stylesHover: {
+ dim: 30,
+ color: '#fcc'
+ },
+ duration: 600
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ enable - (boolean) Default's *false*. Whether to enable this option.
+ type - (string) Default's *auto*. Use this to attach the hover/click events in the nodes or the nodes labels (if they have been defined as DOM elements: 'HTML' or 'SVG', see for more details). The default 'auto' value will set NodeStyles to the same type defined for .
+ stylesHover - (boolean|object) Default's *false*. An object with node styles just like the ones defined for or *false* otherwise.
+ stylesClick - (boolean|object) Default's *false*. An object with node styles just like the ones defined for or *false* otherwise.
+*/
+
+Options.NodeStyles = {
+ $extend: false,
+
+ enable: false,
+ type: 'auto',
+ stylesHover: false,
+ stylesClick: false
+};
+
+
+/*
+ * File: Options.Events.js
+ *
+*/
+
+/*
+ Object: Options.Events
+
+ Configuration for adding mouse/touch event handlers to Nodes.
+
+ Syntax:
+
+ (start code js)
+ Options.Events = {
+ enable: false,
+ enableForEdges: false,
+ type: 'auto',
+ onClick: $.empty,
+ onRightClick: $.empty,
+ onMouseMove: $.empty,
+ onMouseEnter: $.empty,
+ onMouseLeave: $.empty,
+ onDragStart: $.empty,
+ onDragMove: $.empty,
+ onDragCancel: $.empty,
+ onDragEnd: $.empty,
+ onTouchStart: $.empty,
+ onTouchMove: $.empty,
+ onTouchEnd: $.empty,
+ onTouchCancel: $.empty,
+ onMouseWheel: $.empty
+ };
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ Events: {
+ enable: true,
+ onClick: function(node, eventInfo, e) {
+ viz.doSomething();
+ },
+ onMouseEnter: function(node, eventInfo, e) {
+ viz.canvas.getElement().style.cursor = 'pointer';
+ },
+ onMouseLeave: function(node, eventInfo, e) {
+ viz.canvas.getElement().style.cursor = '';
+ }
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ enable - (boolean) Default's *false*. Whether to enable the Event system.
+ enableForEdges - (boolean) Default's *false*. Whether to track events also in arcs. If *true* the same callbacks -described below- are used for nodes *and* edges. A simple duck type check for edges is to check for *node.nodeFrom*.
+ type - (string) Default's 'auto'. Whether to attach the events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. 'auto' is set when you let the *type* parameter decide this.
+ onClick(node, eventInfo, e) - Triggered when a user performs a click in the canvas. *node* is the clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onRightClick(node, eventInfo, e) - Triggered when a user performs a right click in the canvas. *node* is the right clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onMouseMove(node, eventInfo, e) - Triggered when the user moves the mouse. *node* is the under the cursor as it's moving over the canvas or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onMouseEnter(node, eventInfo, e) - Triggered when a user moves the mouse over a node. *node* is the that the mouse just entered. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onMouseLeave(node, eventInfo, e) - Triggered when the user mouse-outs a node. *node* is the 'mouse-outed'. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onDragStart(node, eventInfo, e) - Triggered when the user mouse-downs over a node. *node* is the being pressed. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onDragMove(node, eventInfo, e) - Triggered when a user, after pressing the mouse button over a node, moves the mouse around. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onDragEnd(node, eventInfo, e) - Triggered when a user finished dragging a node. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onDragCancel(node, eventInfo, e) - Triggered when the user releases the mouse button over a that wasn't dragged (i.e. the user didn't perform any mouse movement after pressing the mouse button). *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas.
+ onTouchStart(node, eventInfo, e) - Behaves just like onDragStart.
+ onTouchMove(node, eventInfo, e) - Behaves just like onDragMove.
+ onTouchEnd(node, eventInfo, e) - Behaves just like onDragEnd.
+ onTouchCancel(node, eventInfo, e) - Behaves just like onDragCancel.
+ onMouseWheel(delta, e) - Triggered when the user uses the mouse scroll over the canvas. *delta* is 1 or -1 depending on the sense of the mouse scroll.
+*/
+
+Options.Events = {
+ $extend: false,
+
+ enable: false,
+ enableForEdges: false,
+ type: 'auto',
+ onClick: $.empty,
+ onRightClick: $.empty,
+ onMouseMove: $.empty,
+ onMouseEnter: $.empty,
+ onMouseLeave: $.empty,
+ onDragStart: $.empty,
+ onDragMove: $.empty,
+ onDragCancel: $.empty,
+ onDragEnd: $.empty,
+ onTouchStart: $.empty,
+ onTouchMove: $.empty,
+ onTouchEnd: $.empty,
+ onMouseWheel: $.empty
+};
+
+/*
+ * File: Options.Navigation.js
+ *
+*/
+
+/*
+ Object: Options.Navigation
+
+ Panning and zooming options for Graph/Tree based visualizations. These options are implemented
+ by all visualizations except charts (, and ).
+
+ Syntax:
+
+ (start code js)
+
+ Options.Navigation = {
+ enable: false,
+ type: 'auto',
+ panning: false, //true, 'avoid nodes'
+ zooming: false
+ };
+
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ Navigation: {
+ enable: true,
+ panning: 'avoid nodes',
+ zooming: 20
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ enable - (boolean) Default's *false*. Whether to enable Navigation capabilities.
+ type - (string) Default's 'auto'. Whether to attach the navigation events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. When 'auto' set when you let the *type* parameter decide this.
+ panning - (boolean|string) Default's *false*. Set this property to *true* if you want to add Drag and Drop panning support to the visualization. You can also set this parameter to 'avoid nodes' to enable DnD panning but disable it if the DnD is taking place over a node. This is useful when some other events like Drag & Drop for nodes are added to .
+ zooming - (boolean|number) Default's *false*. Set this property to a numeric value to turn mouse-scroll zooming on. The number will be proportional to the mouse-scroll sensitivity.
+
+*/
+
+Options.Navigation = {
+ $extend: false,
+
+ enable: false,
+ type: 'auto',
+ panning: false, //true | 'avoid nodes'
+ zooming: false
+};
+
+/*
+ * File: Options.Controller.js
+ *
+*/
+
+/*
+ Object: Options.Controller
+
+ Provides controller methods. Controller methods are callback functions that get called at different stages
+ of the animation, computing or plotting of the visualization.
+
+ Implemented by:
+
+ All visualizations except charts (, and ).
+
+ Syntax:
+
+ (start code js)
+
+ Options.Controller = {
+ onBeforeCompute: $.empty,
+ onAfterCompute: $.empty,
+ onCreateLabel: $.empty,
+ onPlaceLabel: $.empty,
+ onComplete: $.empty,
+ onBeforePlotLine:$.empty,
+ onAfterPlotLine: $.empty,
+ onBeforePlotNode:$.empty,
+ onAfterPlotNode: $.empty,
+ request: false
+ };
+
+ (end code)
+
+ Example:
+
+ (start code js)
+ var viz = new $jit.Viz({
+ onBeforePlotNode: function(node) {
+ if(node.selected) {
+ node.setData('color', '#ffc');
+ } else {
+ node.removeData('color');
+ }
+ },
+ onBeforePlotLine: function(adj) {
+ if(adj.nodeFrom.selected && adj.nodeTo.selected) {
+ adj.setData('color', '#ffc');
+ } else {
+ adj.removeData('color');
+ }
+ },
+ onAfterCompute: function() {
+ alert("computed!");
+ }
+ });
+ (end code)
+
+ Parameters:
+
+ onBeforeCompute(node) - This method is called right before performing all computations and animations. The selected is passed as parameter.
+ onAfterCompute() - This method is triggered after all animations or computations ended.
+ onCreateLabel(domElement, node) - This method receives a new label DIV element as first parameter, and the corresponding as second parameter. This method will only be called once for each label. This method is useful when adding events or styles to the labels used by the JIT.
+ onPlaceLabel(domElement, node) - This method receives a label DIV element as first parameter and the corresponding as second parameter. This method is called each time a label has been placed in the visualization, for example at each step of an animation, and thus it allows you to update the labels properties, such as size or position. Note that onPlaceLabel will be triggered after updating the labels positions. That means that, for example, the left and top css properties are already updated to match the nodes positions. Width and height properties are not set however.
+ onBeforePlotNode(node) - This method is triggered right before plotting each . This method is useful for changing a node style right before plotting it.
+ onAfterPlotNode(node) - This method is triggered right after plotting each .
+ onBeforePlotLine(adj) - This method is triggered right before plotting a . This method is useful for adding some styles to a particular edge before being plotted.
+ onAfterPlotLine(adj) - This method is triggered right after plotting a .
+
+ *Used in , and visualizations*
+
+ request(nodeId, level, onComplete) - This method is used for buffering information into the visualization. When clicking on an empty node, the visualization will make a request for this node's subtrees, specifying a given level for this subtree (defined by _levelsToShow_). Once the request is completed, the onComplete callback should be called with the given result. This is useful to provide on-demand information into the visualizations withought having to load the entire information from start. The parameters used by this method are _nodeId_, which is the id of the root of the subtree to request, _level_ which is the depth of the subtree to be requested (0 would mean just the root node). _onComplete_ is an object having the callback method _onComplete.onComplete(json)_ that should be called once the json has been retrieved.
+
+ */
+Options.Controller = {
+ $extend: true,
+
+ onBeforeCompute: $.empty,
+ onAfterCompute: $.empty,
+ onCreateLabel: $.empty,
+ onPlaceLabel: $.empty,
+ onComplete: $.empty,
+ onBeforePlotLine:$.empty,
+ onAfterPlotLine: $.empty,
+ onBeforePlotNode:$.empty,
+ onAfterPlotNode: $.empty,
+ request: false
+};
+
+
+/*
+ * File: Extras.js
+ *
+ * Provides Extras such as Tips and Style Effects.
+ *
+ * Description:
+ *
+ * Provides the and classes and functions.
+ *
+ */
+
+/*
+ * Manager for mouse events (clicking and mouse moving).
+ *
+ * This class is used for registering objects implementing onClick
+ * and onMousemove methods. These methods are called when clicking or
+ * moving the mouse around the Canvas.
+ * For now, and are classes implementing these methods.
+ *
+ */
+var ExtrasInitializer = {
+ initialize: function(className, viz) {
+ this.viz = viz;
+ this.canvas = viz.canvas;
+ this.config = viz.config[className];
+ this.nodeTypes = viz.fx.nodeTypes;
+ var type = this.config.type;
+ this.dom = type == 'auto'? (viz.config.Label.type != 'Native') : (type != 'Native');
+ this.labelContainer = this.dom && viz.labels.getLabelContainer();
+ this.isEnabled() && this.initializePost();
+ },
+ initializePost: $.empty,
+ setAsProperty: $.lambda(false),
+ isEnabled: function() {
+ return this.config.enable;
+ },
+ isLabel: function(e, win, group) {
+ e = $.event.get(e, win);
+ var labelContainer = this.labelContainer,
+ target = e.target || e.srcElement,
+ related = e.relatedTarget;
+ if(group) {
+ return related && related == this.viz.canvas.getCtx().canvas
+ && !!target && this.isDescendantOf(target, labelContainer);
+ } else {
+ return this.isDescendantOf(target, labelContainer);
+ }
+ },
+ isDescendantOf: function(elem, par) {
+ while(elem && elem.parentNode) {
+ if(elem.parentNode == par)
+ return elem;
+ elem = elem.parentNode;
+ }
+ return false;
+ }
+};
+
+var EventsInterface = {
+ onMouseUp: $.empty,
+ onMouseDown: $.empty,
+ onMouseMove: $.empty,
+ onMouseOver: $.empty,
+ onMouseOut: $.empty,
+ onMouseWheel: $.empty,
+ onTouchStart: $.empty,
+ onTouchMove: $.empty,
+ onTouchEnd: $.empty,
+ onTouchCancel: $.empty
+};
+
+var MouseEventsManager = new Class({
+ initialize: function(viz) {
+ this.viz = viz;
+ this.canvas = viz.canvas;
+ this.node = false;
+ this.edge = false;
+ this.registeredObjects = [];
+ this.attachEvents();
+ },
+
+ attachEvents: function() {
+ var htmlCanvas = this.canvas.getElement(),
+ that = this;
+ htmlCanvas.oncontextmenu = $.lambda(false);
+ $.addEvents(htmlCanvas, {
+ 'mouseup': function(e, win) {
+ var event = $.event.get(e, win);
+ that.handleEvent('MouseUp', e, win,
+ that.makeEventObject(e, win),
+ $.event.isRightClick(event));
+ },
+ 'mousedown': function(e, win) {
+ var event = $.event.get(e, win);
+ that.handleEvent('MouseDown', e, win, that.makeEventObject(e, win),
+ $.event.isRightClick(event));
+ },
+ 'mousemove': function(e, win) {
+ that.handleEvent('MouseMove', e, win, that.makeEventObject(e, win));
+ },
+ 'mouseover': function(e, win) {
+ that.handleEvent('MouseOver', e, win, that.makeEventObject(e, win));
+ },
+ 'mouseout': function(e, win) {
+ that.handleEvent('MouseOut', e, win, that.makeEventObject(e, win));
+ },
+ 'touchstart': function(e, win) {
+ that.handleEvent('TouchStart', e, win, that.makeEventObject(e, win));
+ },
+ 'touchmove': function(e, win) {
+ that.handleEvent('TouchMove', e, win, that.makeEventObject(e, win));
+ },
+ 'touchend': function(e, win) {
+ that.handleEvent('TouchEnd', e, win, that.makeEventObject(e, win));
+ }
+ });
+ //attach mousewheel event
+ var handleMouseWheel = function(e, win) {
+ var event = $.event.get(e, win);
+ var wheel = $.event.getWheel(event);
+ that.handleEvent('MouseWheel', e, win, wheel);
+ };
+ //TODO(nico): this is a horrible check for non-gecko browsers!
+ if(!document.getBoxObjectFor && window.mozInnerScreenX == null) {
+ $.addEvent(htmlCanvas, 'mousewheel', handleMouseWheel);
+ } else {
+ htmlCanvas.addEventListener('DOMMouseScroll', handleMouseWheel, false);
+ }
+ },
+
+ register: function(obj) {
+ this.registeredObjects.push(obj);
+ },
+
+ handleEvent: function() {
+ var args = Array.prototype.slice.call(arguments),
+ type = args.shift();
+ for(var i=0, regs=this.registeredObjects, l=regs.length; i and implemented
+ * by all main visualizations.
+ *
+ */
+var Extras = {
+ initializeExtras: function() {
+ var mem = new MouseEventsManager(this), that = this;
+ $.each(['NodeStyles', 'Tips', 'Navigation', 'Events'], function(k) {
+ var obj = new Extras.Classes[k](k, that);
+ if(obj.isEnabled()) {
+ mem.register(obj);
+ }
+ if(obj.setAsProperty()) {
+ that[k.toLowerCase()] = obj;
+ }
+ });
+ }
+};
+
+Extras.Classes = {};
+/*
+ Class: Events
+
+ This class defines an Event API to be accessed by the user.
+ The methods implemented are the ones defined in the object.
+*/
+
+Extras.Classes.Events = new Class({
+ Implements: [ExtrasInitializer, EventsInterface],
+
+ initializePost: function() {
+ this.fx = this.viz.fx;
+ this.ntypes = this.viz.fx.nodeTypes;
+ this.etypes = this.viz.fx.edgeTypes;
+
+ this.hovered = false;
+ this.pressed = false;
+ this.touched = false;
+
+ this.touchMoved = false;
+ this.moved = false;
+
+ },
+
+ setAsProperty: $.lambda(true),
+
+ onMouseUp: function(e, win, event, isRightClick) {
+ var evt = $.event.get(e, win);
+ if(!this.moved) {
+ if(isRightClick) {
+ this.config.onRightClick(this.hovered, event, evt);
+ } else {
+ this.config.onClick(this.pressed, event, evt);
+ }
+ }
+ if(this.pressed) {
+ if(this.moved) {
+ this.config.onDragEnd(this.pressed, event, evt);
+ } else {
+ this.config.onDragCancel(this.pressed, event, evt);
+ }
+ this.pressed = this.moved = false;
+ }
+ },
+
+ onMouseOut: function(e, win, event) {
+ //mouseout a label
+ var evt = $.event.get(e, win), label;
+ if(this.dom && (label = this.isLabel(e, win, true))) {
+ this.config.onMouseLeave(this.viz.graph.getNode(label.id),
+ event, evt);
+ this.hovered = false;
+ return;
+ }
+ //mouseout canvas
+ var rt = evt.relatedTarget,
+ canvasWidget = this.canvas.getElement();
+ while(rt && rt.parentNode) {
+ if(canvasWidget == rt.parentNode) return;
+ rt = rt.parentNode;
+ }
+ if(this.hovered) {
+ this.config.onMouseLeave(this.hovered,
+ event, evt);
+ this.hovered = false;
+ }
+ },
+
+ onMouseOver: function(e, win, event) {
+ //mouseover a label
+ var evt = $.event.get(e, win), label;
+ if(this.dom && (label = this.isLabel(e, win, true))) {
+ this.hovered = this.viz.graph.getNode(label.id);
+ this.config.onMouseEnter(this.hovered,
+ event, evt);
+ }
+ },
+
+ onMouseMove: function(e, win, event) {
+ var label, evt = $.event.get(e, win);
+ if(this.pressed) {
+ this.moved = true;
+ this.config.onDragMove(this.pressed, event, evt);
+ return;
+ }
+ if(this.dom) {
+ this.config.onMouseMove(this.hovered,
+ event, evt);
+ } else {
+ if(this.hovered) {
+ var hn = this.hovered;
+ var geom = hn.nodeFrom? this.etypes[hn.getData('type')] : this.ntypes[hn.getData('type')];
+ var contains = geom && geom.contains
+ && geom.contains.call(this.fx, hn, event.getPos());
+ if(contains) {
+ this.config.onMouseMove(hn, event, evt);
+ return;
+ } else {
+ this.config.onMouseLeave(hn, event, evt);
+ this.hovered = false;
+ }
+ }
+ if(this.hovered = (event.getNode() || (this.config.enableForEdges && event.getEdge()))) {
+ this.config.onMouseEnter(this.hovered, event, evt);
+ } else {
+ this.config.onMouseMove(false, event, evt);
+ }
+ }
+ },
+
+ onMouseWheel: function(e, win, delta) {
+ this.config.onMouseWheel(delta, $.event.get(e, win));
+ },
+
+ onMouseDown: function(e, win, event) {
+
+ // START METAMAPS CODE
+ var evt = $.event.get(e, win);
+ this.pressed = event.getNode() || (this.config.enableForEdges && event.getEdge());
+ // END METAMAPS CODE
+ // ORIGINAL CODE
+ /*var evt = $.event.get(e, win), label;
+ if(this.dom) {
+ if(label = this.isLabel(e, win)) {
+ this.pressed = this.viz.graph.getNode(label.id);
+ }
+ } else {
+ this.pressed = event.getNode() || (this.config.enableForEdges && event.getEdge());
+ } */
+ this.pressed && this.config.onDragStart(this.pressed, event, evt);
+ },
+
+ onTouchStart: function(e, win, event) {
+ var evt = $.event.get(e, win), label;
+ if(this.dom && (label = this.isLabel(e, win))) {
+ this.touched = this.viz.graph.getNode(label.id);
+ } else {
+ this.touched = event.getNode() || (this.config.enableForEdges && event.getEdge());
+ }
+ this.touched && this.config.onTouchStart(this.touched, event, evt);
+ },
+
+ onTouchMove: function(e, win, event) {
+ var evt = $.event.get(e, win);
+ if(this.touched) {
+ this.touchMoved = true;
+ this.config.onTouchMove(this.touched, event, evt);
+ }
+ },
+
+ onTouchEnd: function(e, win, event) {
+ var evt = $.event.get(e, win);
+ if(this.touched) {
+ if(this.touchMoved) {
+ this.config.onTouchEnd(this.touched, event, evt);
+ } else {
+ this.config.onTouchCancel(this.touched, event, evt);
+ }
+ this.touched = this.touchMoved = false;
+ }
+ }
+});
+
+/*
+ Class: Tips
+
+ A class containing tip related functions. This class is used internally.
+
+ Used by:
+
+ , , , , , ,
+
+ See also:
+
+
+*/
+
+Extras.Classes.Tips = new Class({
+ Implements: [ExtrasInitializer, EventsInterface],
+
+ initializePost: function() {
+ //add DOM tooltip
+ if(document.body) {
+ var tip = $('_tooltip') || document.createElement('div');
+ tip.id = '_tooltip';
+ tip.className = 'tip';
+ $.extend(tip.style, {
+ position: 'absolute',
+ display: 'none',
+ zIndex: 13000
+ });
+ document.body.appendChild(tip);
+ this.tip = tip;
+ this.node = false;
+ }
+ },
+
+ setAsProperty: $.lambda(true),
+
+ onMouseOut: function(e, win) {
+ //mouseout a label
+ var evt = $.event.get(e, win);
+ if(this.dom && this.isLabel(e, win, true)) {
+ this.hide(true);
+ return;
+ }
+ //mouseout canvas
+ var rt = e.relatedTarget,
+ canvasWidget = this.canvas.getElement();
+ while(rt && rt.parentNode) {
+ if(canvasWidget == rt.parentNode) return;
+ rt = rt.parentNode;
+ }
+ this.hide(false);
+ },
+
+ onMouseOver: function(e, win) {
+ //mouseover a label
+ var label;
+ if(this.dom && (label = this.isLabel(e, win, false))) {
+ this.node = this.viz.graph.getNode(label.id);
+ this.config.onShow(this.tip, this.node, label);
+ }
+ },
+
+ onMouseMove: function(e, win, opt) {
+ if(this.dom && this.isLabel(e, win)) {
+ this.setTooltipPosition($.event.getPos(e, win));
+ }
+ if(!this.dom) {
+ var node = opt.getNode();
+ if(!node) {
+ this.hide(true);
+ return;
+ }
+ if(this.config.force || !this.node || this.node.id != node.id) {
+ this.node = node;
+ this.config.onShow(this.tip, node, opt.getContains());
+ }
+ this.setTooltipPosition($.event.getPos(e, win));
+ }
+ },
+
+ setTooltipPosition: function(pos) {
+ var tip = this.tip,
+ style = tip.style,
+ cont = this.config;
+ style.display = '';
+ //get window dimensions
+ var win = {
+ 'height': document.body.clientHeight,
+ 'width': document.body.clientWidth
+ };
+ //get tooltip dimensions
+ var obj = {
+ 'width': tip.offsetWidth,
+ 'height': tip.offsetHeight
+ };
+ //set tooltip position
+ var x = cont.offsetX, y = cont.offsetY;
+ style.top = ((pos.y + y + obj.height > win.height)?
+ (pos.y - obj.height - y) : pos.y + y) + 'px';
+ style.left = ((pos.x + obj.width + x > win.width)?
+ (pos.x - obj.width - x) : pos.x + x) + 'px';
+ },
+
+ hide: function(triggerCallback) {
+ this.tip.style.display = 'none';
+ triggerCallback && this.config.onHide();
+ }
+});
+
+/*
+ Class: NodeStyles
+
+ Change node styles when clicking or hovering a node. This class is used internally.
+
+ Used by:
+
+ , , , , , ,
+
+ See also:
+
+
+*/
+Extras.Classes.NodeStyles = new Class({
+ Implements: [ExtrasInitializer, EventsInterface],
+
+ initializePost: function() {
+ this.fx = this.viz.fx;
+ this.types = this.viz.fx.nodeTypes;
+ this.nStyles = this.config;
+ this.nodeStylesOnHover = this.nStyles.stylesHover;
+ this.nodeStylesOnClick = this.nStyles.stylesClick;
+ this.hoveredNode = false;
+ this.fx.nodeFxAnimation = new Animation();
+
+ this.down = false;
+ this.move = false;
+ },
+
+ onMouseOut: function(e, win) {
+ this.down = this.move = false;
+ if(!this.hoveredNode) return;
+ //mouseout a label
+ if(this.dom && this.isLabel(e, win, true)) {
+ this.toggleStylesOnHover(this.hoveredNode, false);
+ }
+ //mouseout canvas
+ var rt = e.relatedTarget,
+ canvasWidget = this.canvas.getElement();
+ while(rt && rt.parentNode) {
+ if(canvasWidget == rt.parentNode) return;
+ rt = rt.parentNode;
+ }
+ this.toggleStylesOnHover(this.hoveredNode, false);
+ this.hoveredNode = false;
+ },
+
+ onMouseOver: function(e, win) {
+ //mouseover a label
+ var label;
+ if(this.dom && (label = this.isLabel(e, win, true))) {
+ var node = this.viz.graph.getNode(label.id);
+ if(node.selected) return;
+ this.hoveredNode = node;
+ this.toggleStylesOnHover(this.hoveredNode, true);
+ }
+ },
+
+ onMouseDown: function(e, win, event, isRightClick) {
+ if(isRightClick) return;
+ var label;
+ if(this.dom && (label = this.isLabel(e, win))) {
+ this.down = this.viz.graph.getNode(label.id);
+ } else if(!this.dom) {
+ this.down = event.getNode();
+ }
+ this.move = false;
+ },
+
+ onMouseUp: function(e, win, event, isRightClick) {
+ if(isRightClick) return;
+ if(!this.move) {
+ this.onClick(event.getNode());
+ }
+ this.down = this.move = false;
+ },
+
+ getRestoredStyles: function(node, type) {
+ var restoredStyles = {},
+ nStyles = this['nodeStylesOn' + type];
+ for(var prop in nStyles) {
+ restoredStyles[prop] = node.styles['$' + prop];
+ }
+ return restoredStyles;
+ },
+
+ toggleStylesOnHover: function(node, set) {
+ if(this.nodeStylesOnHover) {
+ this.toggleStylesOn('Hover', node, set);
+ }
+ },
+
+ toggleStylesOnClick: function(node, set) {
+ if(this.nodeStylesOnClick) {
+ this.toggleStylesOn('Click', node, set);
+ }
+ },
+
+ toggleStylesOn: function(type, node, set) {
+ var viz = this.viz;
+ var nStyles = this.nStyles;
+ if(set) {
+ var that = this;
+ if(!node.styles) {
+ node.styles = $.merge(node.data, {});
+ }
+ for(var s in this['nodeStylesOn' + type]) {
+ var $s = '$' + s;
+ if(!($s in node.styles)) {
+ node.styles[$s] = node.getData(s);
+ }
+ }
+ viz.fx.nodeFx($.extend({
+ 'elements': {
+ 'id': node.id,
+ 'properties': that['nodeStylesOn' + type]
+ },
+ transition: Trans.Quart.easeOut,
+ duration:300,
+ fps:40
+ }, this.config));
+ } else {
+ var restoredStyles = this.getRestoredStyles(node, type);
+ viz.fx.nodeFx($.extend({
+ 'elements': {
+ 'id': node.id,
+ 'properties': restoredStyles
+ },
+ transition: Trans.Quart.easeOut,
+ duration:300,
+ fps:40
+ }, this.config));
+ }
+ },
+
+ onClick: function(node) {
+ if(!node) return;
+ var nStyles = this.nodeStylesOnClick;
+ if(!nStyles) return;
+ //if the node is selected then unselect it
+ if(node.selected) {
+ this.toggleStylesOnClick(node, false);
+ delete node.selected;
+ } else {
+ //unselect all selected nodes...
+ this.viz.graph.eachNode(function(n) {
+ if(n.selected) {
+ for(var s in nStyles) {
+ n.setData(s, n.styles['$' + s], 'end');
+ }
+ delete n.selected;
+ }
+ });
+ //select clicked node
+ this.toggleStylesOnClick(node, true);
+ node.selected = true;
+ delete node.hovered;
+ this.hoveredNode = false;
+ }
+ },
+
+ onMouseMove: function(e, win, event) {
+ //if mouse button is down and moving set move=true
+ if(this.down) this.move = true;
+ //already handled by mouseover/out
+ if(this.dom && this.isLabel(e, win)) return;
+ var nStyles = this.nodeStylesOnHover;
+ if(!nStyles) return;
+
+ if(!this.dom) {
+ if(this.hoveredNode) {
+ var geom = this.types[this.hoveredNode.getData('type')];
+ var contains = geom && geom.contains && geom.contains.call(this.fx,
+ this.hoveredNode, event.getPos());
+ if(contains) return;
+ }
+ var node = event.getNode();
+ //if no node is being hovered then just exit
+ if(!this.hoveredNode && !node) return;
+ //if the node is hovered then exit
+ if(node.hovered) return;
+ //select hovered node
+ if(node && !node.selected) {
+ //check if an animation is running and exit it
+ this.fx.nodeFxAnimation.stopTimer();
+ //unselect all hovered nodes...
+ this.viz.graph.eachNode(function(n) {
+ if(n.hovered && !n.selected) {
+ for(var s in nStyles) {
+ n.setData(s, n.styles['$' + s], 'end');
+ }
+ delete n.hovered;
+ }
+ });
+ //select hovered node
+ node.hovered = true;
+ this.hoveredNode = node;
+ this.toggleStylesOnHover(node, true);
+ } else if(this.hoveredNode && !this.hoveredNode.selected) {
+ //check if an animation is running and exit it
+ this.fx.nodeFxAnimation.stopTimer();
+ //unselect hovered node
+ this.toggleStylesOnHover(this.hoveredNode, false);
+ delete this.hoveredNode.hovered;
+ this.hoveredNode = false;
+ }
+ }
+ }
+});
+
+Extras.Classes.Navigation = new Class({
+ Implements: [ExtrasInitializer, EventsInterface],
+
+ initializePost: function() {
+ this.pos = false;
+ this.pressed = false;
+ },
+
+ onMouseWheel: function(e, win, scroll) {
+ if(!this.config.zooming) return;
+
+ // START METAMAPS CODE
+ if (e.target.id != 'infovis-canvas') return;
+ // END METAMAPS CODE
+
+ $.event.stop($.event.get(e, win));
+ var val = this.config.zooming / 1000,
+ ans = 1 + scroll * val;
+
+ // START METAMAPS CODE
+ if (ans > 1) {
+ if (5 >= this.canvas.scaleOffsetX) {
+ this.canvas.scale(ans, ans);
+ }
+ }
+ else if (ans < 1) {
+ if (this.canvas.scaleOffsetX >= 0.2) {
+ this.canvas.scale(ans, ans);
+ }
+ }
+ // END METAMAPS CODE
+ // ORIGINAL CODE this.canvas.scale(ans, ans);
+ },
+
+ onMouseDown: function(e, win, eventInfo) {
+ if(!this.config.panning) return;
+
+ //START METAMAPS CODE
+ Metamaps.Mouse.changeInX = 0;
+ Metamaps.Mouse.changeInY = 0;
+ if((this.config.panning == 'avoid nodes' && eventInfo.getNode()) || eventInfo.getEdge()) return;
+ // END METAMAPS CODE
+ // ORIGINAl CODE if(this.config.panning == 'avoid nodes' && (this.dom? this.isLabel(e, win) : eventInfo.getNode())) return;
+
+ this.pressed = true;
+
+ //START METAMAPS CODE
+ if (!Metamaps.Mouse.boxStartCoordinates && e.shiftKey) {
+ Metamaps.Mouse.boxStartCoordinates = eventInfo.getPos();
+ }
+ Metamaps.Mouse.didPan = false;
+ // END METAMAPS CODE
+
+ this.pos = eventInfo.getPos();
+ var canvas = this.canvas,
+ ox = canvas.translateOffsetX,
+ oy = canvas.translateOffsetY,
+ sx = canvas.scaleOffsetX,
+ sy = canvas.scaleOffsetY;
+ this.pos.x *= sx;
+ this.pos.x += ox;
+ this.pos.y *= sy;
+ this.pos.y += oy;
+ },
+
+ onMouseMove: function(e, win, eventInfo) {
+ if(!this.config.panning) return;
+ if(!this.pressed) return;
+ if(this.config.panning == 'avoid nodes' && (this.dom? this.isLabel(e, win) : eventInfo.getNode())) return;
+
+ // START METAMAPS CODE
+ if (!Metamaps.Mouse.boxStartCoordinates && e.shiftKey) {
+ Metamaps.Visualize.mGraph.busy = true;
+ Metamaps.boxStartCoordinates = eventInfo.getPos();
+ return;
+ }
+ if (Metamaps.Mouse.boxStartCoordinates && e.shiftKey) {
+ Metamaps.Visualize.mGraph.busy = true;
+ Metamaps.JIT.drawSelectBox(eventInfo,e);
+ return;
+ }
+ if (e.target.id != 'infovis-canvas') {
+ this.pressed = false;
+ return;
+ }
+ Metamaps.Mouse.didPan = true;
+ // END METAMAPS CODE
+
+ var thispos = this.pos,
+ currentPos = eventInfo.getPos(),
+ canvas = this.canvas,
+ ox = canvas.translateOffsetX,
+ oy = canvas.translateOffsetY,
+ sx = canvas.scaleOffsetX,
+ sy = canvas.scaleOffsetY;
+ currentPos.x *= sx;
+ currentPos.y *= sy;
+ currentPos.x += ox;
+ currentPos.y += oy;
+ var x = currentPos.x - thispos.x,
+ y = currentPos.y - thispos.y;
+
+ // START METAMAPS CODE
+ Metamaps.Mouse.changeInX = x;
+ Metamaps.Mouse.changeInY = y;
+ // END METAMAPS CODE
+
+ this.pos = currentPos;
+ this.canvas.translate(x * 1/sx, y * 1/sy);
+ },
+
+ onMouseUp: function(e, win, eventInfo, isRightClick) {
+ if(!this.config.panning) return;
+ this.pressed = false;
+
+ // START METAMAPS CODE
+ if (Metamaps.Mouse.didPan) Metamaps.JIT.SmoothPanning();
+ // END METAMAPS CODE
+
+ }
+});
+
+
+/*
+ * File: Canvas.js
+ *
+ */
+
+/*
+ Class: Canvas
+
+ A canvas widget used by all visualizations. The canvas object can be accessed by doing *viz.canvas*. If you want to
+ know more about