vchat
Version:
An experimental video chat server/client hybrid
1,569 lines (1,284 loc) • 129 kB
JavaScript
/*! gridster.js - v0.5.6 - 2014-09-25
* http://gridster.net/
* Copyright (c) 2014 ducksboard; Licensed MIT */
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('gridster-coords', ['jquery'], factory);
} else {
root.GridsterCoords = factory(root.$ || root.jQuery);
}
}(this, function($) {
/**
* Creates objects with coordinates (x1, y1, x2, y2, cx, cy, width, height)
* to simulate DOM elements on the screen.
* Coords is used by Gridster to create a faux grid with any DOM element can
* collide.
*
* @class Coords
* @param {HTMLElement|Object} obj The jQuery HTMLElement or a object with: left,
* top, width and height properties.
* @return {Object} Coords instance.
* @constructor
*/
function Coords(obj) {
if (obj[0] && $.isPlainObject(obj[0])) {
this.data = obj[0];
}else {
this.el = obj;
}
this.isCoords = true;
this.coords = {};
this.init();
return this;
}
var fn = Coords.prototype;
fn.init = function(){
this.set();
this.original_coords = this.get();
};
fn.set = function(update, not_update_offsets) {
var el = this.el;
if (el && !update) {
this.data = el.offset();
this.data.width = el.width();
this.data.height = el.height();
}
if (el && update && !not_update_offsets) {
var offset = el.offset();
this.data.top = offset.top;
this.data.left = offset.left;
}
var d = this.data;
typeof d.left === 'undefined' && (d.left = d.x1);
typeof d.top === 'undefined' && (d.top = d.y1);
this.coords.x1 = d.left;
this.coords.y1 = d.top;
this.coords.x2 = d.left + d.width;
this.coords.y2 = d.top + d.height;
this.coords.cx = d.left + (d.width / 2);
this.coords.cy = d.top + (d.height / 2);
this.coords.width = d.width;
this.coords.height = d.height;
this.coords.el = el || false ;
return this;
};
fn.update = function(data){
if (!data && !this.el) {
return this;
}
if (data) {
var new_data = $.extend({}, this.data, data);
this.data = new_data;
return this.set(true, true);
}
this.set(true);
return this;
};
fn.get = function(){
return this.coords;
};
fn.destroy = function() {
this.el.removeData('coords');
delete this.el;
};
//jQuery adapter
$.fn.coords = function() {
if (this.data('coords') ) {
return this.data('coords');
}
var ins = new Coords(this, arguments[0]);
this.data('coords', ins);
return ins;
};
return Coords;
}));
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('gridster-collision', ['jquery', 'gridster-coords'], factory);
} else {
root.GridsterCollision = factory(root.$ || root.jQuery,
root.GridsterCoords);
}
}(this, function($, Coords) {
var defaults = {
colliders_context: document.body,
overlapping_region: 'C'
// ,on_overlap: function(collider_data){},
// on_overlap_start : function(collider_data){},
// on_overlap_stop : function(collider_data){}
};
/**
* Detects collisions between a DOM element against other DOM elements or
* Coords objects.
*
* @class Collision
* @uses Coords
* @param {HTMLElement} el The jQuery wrapped HTMLElement.
* @param {HTMLElement|Array} colliders Can be a jQuery collection
* of HTMLElements or an Array of Coords instances.
* @param {Object} [options] An Object with all options you want to
* overwrite:
* @param {String} [options.overlapping_region] Determines when collision
* is valid, depending on the overlapped area. Values can be: 'N', 'S',
* 'W', 'E', 'C' or 'all'. Default is 'C'.
* @param {Function} [options.on_overlap_start] Executes a function the first
* time each `collider ` is overlapped.
* @param {Function} [options.on_overlap_stop] Executes a function when a
* `collider` is no longer collided.
* @param {Function} [options.on_overlap] Executes a function when the
* mouse is moved during the collision.
* @return {Object} Collision instance.
* @constructor
*/
function Collision(el, colliders, options) {
this.options = $.extend(defaults, options);
this.$element = el;
this.last_colliders = [];
this.last_colliders_coords = [];
this.set_colliders(colliders);
this.init();
}
Collision.defaults = defaults;
var fn = Collision.prototype;
fn.init = function() {
this.find_collisions();
};
fn.overlaps = function(a, b) {
var x = false;
var y = false;
if ((b.x1 >= a.x1 && b.x1 <= a.x2) ||
(b.x2 >= a.x1 && b.x2 <= a.x2) ||
(a.x1 >= b.x1 && a.x2 <= b.x2)
) { x = true; }
if ((b.y1 >= a.y1 && b.y1 <= a.y2) ||
(b.y2 >= a.y1 && b.y2 <= a.y2) ||
(a.y1 >= b.y1 && a.y2 <= b.y2)
) { y = true; }
return (x && y);
};
fn.detect_overlapping_region = function(a, b){
var regionX = '';
var regionY = '';
if (a.y1 > b.cy && a.y1 < b.y2) { regionX = 'N'; }
if (a.y2 > b.y1 && a.y2 < b.cy) { regionX = 'S'; }
if (a.x1 > b.cx && a.x1 < b.x2) { regionY = 'W'; }
if (a.x2 > b.x1 && a.x2 < b.cx) { regionY = 'E'; }
return (regionX + regionY) || 'C';
};
fn.calculate_overlapped_area_coords = function(a, b){
var x1 = Math.max(a.x1, b.x1);
var y1 = Math.max(a.y1, b.y1);
var x2 = Math.min(a.x2, b.x2);
var y2 = Math.min(a.y2, b.y2);
return $({
left: x1,
top: y1,
width : (x2 - x1),
height: (y2 - y1)
}).coords().get();
};
fn.calculate_overlapped_area = function(coords){
return (coords.width * coords.height);
};
fn.manage_colliders_start_stop = function(new_colliders_coords, start_callback, stop_callback){
var last = this.last_colliders_coords;
for (var i = 0, il = last.length; i < il; i++) {
if ($.inArray(last[i], new_colliders_coords) === -1) {
start_callback.call(this, last[i]);
}
}
for (var j = 0, jl = new_colliders_coords.length; j < jl; j++) {
if ($.inArray(new_colliders_coords[j], last) === -1) {
stop_callback.call(this, new_colliders_coords[j]);
}
}
};
fn.find_collisions = function(player_data_coords){
var self = this;
var overlapping_region = this.options.overlapping_region;
var colliders_coords = [];
var colliders_data = [];
var $colliders = (this.colliders || this.$colliders);
var count = $colliders.length;
var player_coords = self.$element.coords()
.update(player_data_coords || false).get();
while(count--){
var $collider = self.$colliders ?
$($colliders[count]) : $colliders[count];
var $collider_coords_ins = ($collider.isCoords) ?
$collider : $collider.coords();
var collider_coords = $collider_coords_ins.get();
var overlaps = self.overlaps(player_coords, collider_coords);
if (!overlaps) {
continue;
}
var region = self.detect_overlapping_region(
player_coords, collider_coords);
//todo: make this an option
if (region === overlapping_region || overlapping_region === 'all') {
var area_coords = self.calculate_overlapped_area_coords(
player_coords, collider_coords);
var area = self.calculate_overlapped_area(area_coords);
var collider_data = {
area: area,
area_coords : area_coords,
region: region,
coords: collider_coords,
player_coords: player_coords,
el: $collider
};
if (self.options.on_overlap) {
self.options.on_overlap.call(this, collider_data);
}
colliders_coords.push($collider_coords_ins);
colliders_data.push(collider_data);
}
}
if (self.options.on_overlap_stop || self.options.on_overlap_start) {
this.manage_colliders_start_stop(colliders_coords,
self.options.on_overlap_start, self.options.on_overlap_stop);
}
this.last_colliders_coords = colliders_coords;
return colliders_data;
};
fn.get_closest_colliders = function(player_data_coords){
var colliders = this.find_collisions(player_data_coords);
colliders.sort(function(a, b) {
/* if colliders are being overlapped by the "C" (center) region,
* we have to set a lower index in the array to which they are placed
* above in the grid. */
if (a.region === 'C' && b.region === 'C') {
if (a.coords.y1 < b.coords.y1 || a.coords.x1 < b.coords.x1) {
return - 1;
}else{
return 1;
}
}
if (a.area < b.area) {
return 1;
}
return 1;
});
return colliders;
};
fn.set_colliders = function(colliders) {
if (typeof colliders === 'string' || colliders instanceof $) {
this.$colliders = $(colliders,
this.options.colliders_context).not(this.$element);
}else{
this.colliders = $(colliders);
}
};
//jQuery adapter
$.fn.collision = function(collider, options) {
return new Collision( this, collider, options );
};
return Collision;
}));
;(function(window, undefined) {
/* Delay, debounce and throttle functions taken from underscore.js
*
* Copyright (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and
* Investigative Reporters & Editors
*
* 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.
*/
window.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
window.debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
window.throttle = function(func, wait) {
var context, args, timeout, throttling, more, result;
var whenDone = debounce(
function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) func.apply(context, args);
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
result = func.apply(context, args);
}
whenDone();
throttling = true;
return result;
};
};
})(window);
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('gridster-draggable', ['jquery'], factory);
} else {
root.GridsterDraggable = factory(root.$ || root.jQuery);
}
}(this, function($) {
var defaults = {
items: 'li',
distance: 1,
limit: true,
offset_left: 0,
autoscroll: true,
ignore_dragging: ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'], // or function
handle: null,
container_width: 0, // 0 == auto
move_element: true,
helper: false, // or 'clone'
remove_helper: true
// drag: function(e) {},
// start : function(e, ui) {},
// stop : function(e) {}
};
var $window = $(window);
var dir_map = { x : 'left', y : 'top' };
var isTouch = !!('ontouchstart' in window);
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
var idCounter = 0;
var uniqId = function() {
return ++idCounter + '';
};
/**
* Basic drag implementation for DOM elements inside a container.
* Provide start/stop/drag callbacks.
*
* @class Draggable
* @param {HTMLElement} el The HTMLelement that contains all the widgets
* to be dragged.
* @param {Object} [options] An Object with all options you want to
* overwrite:
* @param {HTMLElement|String} [options.items] Define who will
* be the draggable items. Can be a CSS Selector String or a
* collection of HTMLElements.
* @param {Number} [options.distance] Distance in pixels after mousedown
* the mouse must move before dragging should start.
* @param {Boolean} [options.limit] Constrains dragging to the width of
* the container
* @param {Object|Function} [options.ignore_dragging] Array of node names
* that sould not trigger dragging, by default is `['INPUT', 'TEXTAREA',
* 'SELECT', 'BUTTON']`. If a function is used return true to ignore dragging.
* @param {offset_left} [options.offset_left] Offset added to the item
* that is being dragged.
* @param {Number} [options.drag] Executes a callback when the mouse is
* moved during the dragging.
* @param {Number} [options.start] Executes a callback when the drag
* starts.
* @param {Number} [options.stop] Executes a callback when the drag stops.
* @return {Object} Returns `el`.
* @constructor
*/
function Draggable(el, options) {
this.options = $.extend({}, defaults, options);
this.$document = $(document);
this.$container = $(el);
this.$dragitems = $(this.options.items, this.$container);
this.is_dragging = false;
this.player_min_left = 0 + this.options.offset_left;
this.id = uniqId();
this.ns = '.gridster-draggable-' + this.id;
this.init();
}
Draggable.defaults = defaults;
var fn = Draggable.prototype;
fn.init = function() {
var pos = this.$container.css('position');
this.calculate_dimensions();
this.$container.css('position', pos === 'static' ? 'relative' : pos);
this.disabled = false;
this.events();
$(window).bind(this.nsEvent('resize'),
throttle($.proxy(this.calculate_dimensions, this), 200));
};
fn.nsEvent = function(ev) {
return (ev || '') + this.ns;
};
fn.events = function() {
this.pointer_events = {
start: this.nsEvent('touchstart') + ' ' + this.nsEvent('mousedown'),
move: this.nsEvent('touchmove') + ' ' + this.nsEvent('mousemove'),
end: this.nsEvent('touchend') + ' ' + this.nsEvent('mouseup')
};
this.$container.on(this.nsEvent('selectstart'),
$.proxy(this.on_select_start, this));
this.$container.on(this.pointer_events.start, this.options.items,
$.proxy(this.drag_handler, this));
this.$document.on(this.pointer_events.end, $.proxy(function(e) {
this.is_dragging = false;
if (this.disabled) { return; }
this.$document.off(this.pointer_events.move);
if (this.drag_start) {
this.on_dragstop(e);
}
}, this));
};
fn.get_actual_pos = function($el) {
var pos = $el.position();
return pos;
};
fn.get_mouse_pos = function(e) {
if (e.originalEvent && e.originalEvent.touches) {
var oe = e.originalEvent;
e = oe.touches.length ? oe.touches[0] : oe.changedTouches[0];
}
return {
left: e.clientX,
top: e.clientY
};
};
fn.get_offset = function(e) {
e.preventDefault();
var mouse_actual_pos = this.get_mouse_pos(e);
var diff_x = Math.round(
mouse_actual_pos.left - this.mouse_init_pos.left);
var diff_y = Math.round(mouse_actual_pos.top - this.mouse_init_pos.top);
var left = Math.round(this.el_init_offset.left +
diff_x - this.baseX + $(window).scrollLeft() - this.win_offset_x);
var top = Math.round(this.el_init_offset.top +
diff_y - this.baseY + $(window).scrollTop() - this.win_offset_y);
if (this.options.limit) {
if (left > this.player_max_left) {
left = this.player_max_left;
} else if(left < this.player_min_left) {
left = this.player_min_left;
}
}
return {
position: {
left: left,
top: top
},
pointer: {
left: mouse_actual_pos.left,
top: mouse_actual_pos.top,
diff_left: diff_x + ($(window).scrollLeft() - this.win_offset_x),
diff_top: diff_y + ($(window).scrollTop() - this.win_offset_y)
}
};
};
fn.get_drag_data = function(e) {
var offset = this.get_offset(e);
offset.$player = this.$player;
offset.$helper = this.helper ? this.$helper : this.$player;
return offset;
};
fn.set_limits = function(container_width) {
container_width || (container_width = this.$container.width());
this.player_max_left = (container_width - this.player_width +
- this.options.offset_left);
this.options.container_width = container_width;
return this;
};
fn.scroll_in = function(axis, data) {
var dir_prop = dir_map[axis];
var area_size = 50;
var scroll_inc = 30;
var is_x = axis === 'x';
var window_size = is_x ? this.window_width : this.window_height;
var doc_size = is_x ? $(document).width() : $(document).height();
var player_size = is_x ? this.$player.width() : this.$player.height();
var next_scroll;
var scroll_offset = $window['scroll' + capitalize(dir_prop)]();
var min_window_pos = scroll_offset;
var max_window_pos = min_window_pos + window_size;
var mouse_next_zone = max_window_pos - area_size; // down/right
var mouse_prev_zone = min_window_pos + area_size; // up/left
var abs_mouse_pos = min_window_pos + data.pointer[dir_prop];
var max_player_pos = (doc_size - window_size + player_size);
if (abs_mouse_pos >= mouse_next_zone) {
next_scroll = scroll_offset + scroll_inc;
if (next_scroll < max_player_pos) {
$window['scroll' + capitalize(dir_prop)](next_scroll);
this['scroll_offset_' + axis] += scroll_inc;
}
}
if (abs_mouse_pos <= mouse_prev_zone) {
next_scroll = scroll_offset - scroll_inc;
if (next_scroll > 0) {
$window['scroll' + capitalize(dir_prop)](next_scroll);
this['scroll_offset_' + axis] -= scroll_inc;
}
}
return this;
};
fn.manage_scroll = function(data) {
this.scroll_in('x', data);
this.scroll_in('y', data);
};
fn.calculate_dimensions = function(e) {
this.window_height = $window.height();
this.window_width = $window.width();
};
fn.drag_handler = function(e) {
var node = e.target.nodeName;
// skip if drag is disabled, or click was not done with the mouse primary button
if (this.disabled || e.which !== 1 && !isTouch) {
return;
}
if (this.ignore_drag(e)) {
return;
}
var self = this;
var first = true;
this.$player = $(e.currentTarget);
this.el_init_pos = this.get_actual_pos(this.$player);
this.mouse_init_pos = this.get_mouse_pos(e);
this.offsetY = this.mouse_init_pos.top - this.el_init_pos.top;
this.$document.on(this.pointer_events.move, function(mme) {
var mouse_actual_pos = self.get_mouse_pos(mme);
var diff_x = Math.abs(
mouse_actual_pos.left - self.mouse_init_pos.left);
var diff_y = Math.abs(
mouse_actual_pos.top - self.mouse_init_pos.top);
if (!(diff_x > self.options.distance ||
diff_y > self.options.distance)
) {
return false;
}
if (first) {
first = false;
self.on_dragstart.call(self, mme);
return false;
}
if (self.is_dragging === true) {
self.on_dragmove.call(self, mme);
}
return false;
});
if (!isTouch) { return false; }
};
fn.on_dragstart = function(e) {
e.preventDefault();
if (this.is_dragging) { return this; }
this.drag_start = this.is_dragging = true;
var offset = this.$container.offset();
this.baseX = Math.round(offset.left);
this.baseY = Math.round(offset.top);
this.initial_container_width = this.options.container_width || this.$container.width();
if (this.options.helper === 'clone') {
this.$helper = this.$player.clone()
.appendTo(this.$container).addClass('helper');
this.helper = true;
} else {
this.helper = false;
}
this.win_offset_y = $(window).scrollTop();
this.win_offset_x = $(window).scrollLeft();
this.scroll_offset_y = 0;
this.scroll_offset_x = 0;
this.el_init_offset = this.$player.offset();
this.player_width = this.$player.width();
this.player_height = this.$player.height();
this.set_limits(this.options.container_width);
if (this.options.start) {
this.options.start.call(this.$player, e, this.get_drag_data(e));
}
return false;
};
fn.on_dragmove = function(e) {
var data = this.get_drag_data(e);
this.options.autoscroll && this.manage_scroll(data);
if (this.options.move_element) {
(this.helper ? this.$helper : this.$player).css({
'position': 'absolute',
'left' : data.position.left,
'top' : data.position.top
});
}
var last_position = this.last_position || data.position;
data.prev_position = last_position;
if (this.options.drag) {
this.options.drag.call(this.$player, e, data);
}
this.last_position = data.position;
return false;
};
fn.on_dragstop = function(e) {
var data = this.get_drag_data(e);
this.drag_start = false;
if (this.options.stop) {
this.options.stop.call(this.$player, e, data);
}
if (this.helper && this.options.remove_helper) {
this.$helper.remove();
}
return false;
};
fn.on_select_start = function(e) {
if (this.disabled) { return; }
if (this.ignore_drag(e)) {
return;
}
return false;
};
fn.enable = function() {
this.disabled = false;
};
fn.disable = function() {
this.disabled = true;
};
fn.destroy = function() {
this.disable();
this.$container.off(this.ns);
this.$document.off(this.ns);
$(window).off(this.ns);
$.removeData(this.$container, 'drag');
};
fn.ignore_drag = function(event) {
if (this.options.handle) {
return !$(event.target).is(this.options.handle);
}
if ($.isFunction(this.options.ignore_dragging)) {
return this.options.ignore_dragging(event);
}
return $(event.target).is(this.options.ignore_dragging.join(', '));
};
//jQuery adapter
$.fn.drag = function ( options ) {
return new Draggable(this, options);
};
return Draggable;
}));
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery', 'gridster-draggable', 'gridster-collision'], factory);
} else {
root.Gridster = factory(root.$ || root.jQuery, root.GridsterDraggable,
root.GridsterCollision);
}
}(this, function($, Draggable, Collision) {
var defaults = {
namespace: '',
widget_selector: 'li',
widget_margins: [10, 10],
widget_base_dimensions: [400, 225],
extra_rows: 0,
extra_cols: 0,
min_cols: 1,
max_cols: Infinity,
min_rows: 15,
max_size_x: false,
autogrow_cols: false,
maintain_aspect_ratio: false,
autogenerate_stylesheet: true,
avoid_overlapped_widgets: true,
auto_init: true,
serialize_params: function($w, wgd) {
return {
col: wgd.col,
row: wgd.row,
size_x: wgd.size_x,
size_y: wgd.size_y
};
},
collision: {},
draggable: {
items: '.gs-w',
distance: 4,
ignore_dragging: Draggable.defaults.ignore_dragging.slice(0)
},
resize: {
enabled: false,
axes: ['both'],
handle_append_to: '',
handle_class: 'gs-resize-handle',
max_size: [Infinity, Infinity],
min_size: [1, 1]
}
};
/**
* @class Gridster
* @uses Draggable
* @uses Collision
* @param {HTMLElement} el The HTMLelement that contains all the widgets.
* @param {Object} [options] An Object with all options you want to
* overwrite:
* @param {HTMLElement|String} [options.widget_selector] Define who will
* be the draggable widgets. Can be a CSS Selector String or a
* collection of HTMLElements
* @param {Array} [options.widget_margins] Margin between widgets.
* The first index for the horizontal margin (left, right) and
* the second for the vertical margin (top, bottom).
* @param {Array} [options.widget_base_dimensions] Base widget dimensions
* in pixels. The first index for the width and the second for the
* height.
* @param {Number} [options.extra_cols] Add more columns in addition to
* those that have been calculated.
* @param {Number} [options.extra_rows] Add more rows in addition to
* those that have been calculated.
* @param {Number} [options.min_cols] The minimum required columns.
* @param {Number} [options.max_cols] The maximum columns possible (set to null
* for no maximum).
* @param {Number} [options.min_rows] The minimum required rows.
* @param {Number} [options.max_size_x] The maximum number of columns
* that a widget can span.
* @param {Boolean} [options.autogenerate_stylesheet] If true, all the
* CSS required to position all widgets in their respective columns
* and rows will be generated automatically and injected to the
* `<head>` of the document. You can set this to false, and write
* your own CSS targeting rows and cols via data-attributes like so:
* `[data-col="1"] { left: 10px; }`
* @param {Boolean} [options.avoid_overlapped_widgets] Avoid that widgets loaded
* from the DOM can be overlapped. It is helpful if the positions were
* bad stored in the database or if there was any conflict.
* @param {Boolean} [options.auto_init] Automatically call gridster init
* method or not when the plugin is instantiated.
* @param {Function} [options.serialize_params] Return the data you want
* for each widget in the serialization. Two arguments are passed:
* `$w`: the jQuery wrapped HTMLElement, and `wgd`: the grid
* coords object (`col`, `row`, `size_x`, `size_y`).
* @param {Object} [options.collision] An Object with all options for
* Collision class you want to overwrite. See Collision docs for
* more info.
* @param {Object} [options.draggable] An Object with all options for
* Draggable class you want to overwrite. See Draggable docs for more
* info.
* @param {Object|Function} [options.draggable.ignore_dragging] Note that
* if you use a Function, and resize is enabled, you should ignore the
* resize handlers manually (options.resize.handle_class).
* @param {Object} [options.resize] An Object with resize config options.
* @param {Boolean} [options.resize.enabled] Set to true to enable
* resizing.
* @param {Array} [options.resize.axes] Axes in which widgets can be
* resized. Possible values: ['x', 'y', 'both'].
* @param {String} [options.resize.handle_append_to] Set a valid CSS
* selector to append resize handles to.
* @param {String} [options.resize.handle_class] CSS class name used
* by resize handles.
* @param {Array} [options.resize.max_size] Limit widget dimensions
* when resizing. Array values should be integers:
* `[max_cols_occupied, max_rows_occupied]`
* @param {Array} [options.resize.min_size] Limit widget dimensions
* when resizing. Array values should be integers:
* `[min_cols_occupied, min_rows_occupied]`
* @param {Function} [options.resize.start] Function executed
* when resizing starts.
* @param {Function} [otions.resize.resize] Function executed
* during the resizing.
* @param {Function} [options.resize.stop] Function executed
* when resizing stops.
*
* @constructor
*/
function Gridster(el, options) {
this.options = $.extend(true, {}, defaults, options);
this.$el = $(el);
this.$wrapper = this.$el.parent();
this.$widgets = this.$el.children(
this.options.widget_selector).addClass('gs-w');
this.widgets = [];
this.$changed = $([]);
this.wrapper_width = this.$wrapper.width();
this.min_widget_width = (this.options.widget_margins[0] * 2) +
this.options.widget_base_dimensions[0];
this.min_widget_height = (this.options.widget_margins[1] * 2) +
this.options.widget_base_dimensions[1];
this.generated_stylesheets = [];
this.$style_tags = $([]);
this.options.auto_init && this.init();
}
Gridster.defaults = defaults;
Gridster.generated_stylesheets = [];
/**
* Sorts an Array of grid coords objects (representing the grid coords of
* each widget) in ascending way.
*
* @method sort_by_row_asc
* @param {Array} widgets Array of grid coords objects
* @return {Array} Returns the array sorted.
*/
Gridster.sort_by_row_asc = function(widgets) {
widgets = widgets.sort(function(a, b) {
if (!a.row) {
a = $(a).coords().grid;
b = $(b).coords().grid;
}
if (a.row > b.row) {
return 1;
}
return -1;
});
return widgets;
};
/**
* Sorts an Array of grid coords objects (representing the grid coords of
* each widget) placing first the empty cells upper left.
*
* @method sort_by_row_and_col_asc
* @param {Array} widgets Array of grid coords objects
* @return {Array} Returns the array sorted.
*/
Gridster.sort_by_row_and_col_asc = function(widgets) {
widgets = widgets.sort(function(a, b) {
if (a.row > b.row || a.row === b.row && a.col > b.col) {
return 1;
}
return -1;
});
return widgets;
};
/**
* Sorts an Array of grid coords objects by column (representing the grid
* coords of each widget) in ascending way.
*
* @method sort_by_col_asc
* @param {Array} widgets Array of grid coords objects
* @return {Array} Returns the array sorted.
*/
Gridster.sort_by_col_asc = function(widgets) {
widgets = widgets.sort(function(a, b) {
if (a.col > b.col) {
return 1;
}
return -1;
});
return widgets;
};
/**
* Sorts an Array of grid coords objects (representing the grid coords of
* each widget) in descending way.
*
* @method sort_by_row_desc
* @param {Array} widgets Array of grid coords objects
* @return {Array} Returns the array sorted.
*/
Gridster.sort_by_row_desc = function(widgets) {
widgets = widgets.sort(function(a, b) {
if (a.row + a.size_y < b.row + b.size_y) {
return 1;
}
return -1;
});
return widgets;
};
/** Instance Methods **/
var fn = Gridster.prototype;
fn.init = function() {
this.options.resize.enabled && this.setup_resize();
this.generate_grid_and_stylesheet();
this.get_widgets_from_DOM();
this.set_dom_grid_height();
this.set_dom_grid_width();
this.$wrapper.addClass('ready');
this.draggable();
this.options.resize.enabled && this.resizable();
$(window).bind('resize.gridster', throttle(
$.proxy(this.recalculate_faux_grid, this), 200));
};
/**
* Disables dragging.
*
* @method disable
* @return {Class} Returns the instance of the Gridster Class.
*/
fn.disable = function() {
this.$wrapper.find('.player-revert').removeClass('player-revert');
this.drag_api.disable();
return this;
};
/**
* Enables dragging.
*
* @method enable
* @return {Class} Returns the instance of the Gridster Class.
*/
fn.enable = function() {
this.drag_api.enable();
return this;
};
/**
* Disables drag-and-drop widget resizing.
*
* @method disable
* @return {Class} Returns instance of gridster Class.
*/
fn.disable_resize = function() {
this.$el.addClass('gs-resize-disabled');
this.resize_api.disable();
return this;
};
/**
* Enables drag-and-drop widget resizing.
*
* @method enable
* @return {Class} Returns instance of gridster Class.
*/
fn.enable_resize = function() {
this.$el.removeClass('gs-resize-disabled');
this.resize_api.enable();
return this;
};
/**
* Add a new widget to the grid.
*
* @method add_widget
* @param {String|HTMLElement} html The string representing the HTML of the widget
* or the HTMLElement.
* @param {Number} [size_x] The nº of rows the widget occupies horizontally.
* @param {Number} [size_y] The nº of columns the widget occupies vertically.
* @param {Number} [col] The column the widget should start in.
* @param {Number} [row] The row the widget should start in.
* @param {Array} [max_size] max_size Maximun size (in units) for width and height.
* @param {Array} [min_size] min_size Minimum size (in units) for width and height.
* @return {HTMLElement} Returns the jQuery wrapped HTMLElement representing.
* the widget that was just created.
*/
fn.add_widget = function(html, size_x, size_y, col, row, max_size, min_size) {
var pos;
size_x || (size_x = 1);
size_y || (size_y = 1);
if (!col & !row) {
pos = this.next_position(size_x, size_y);
} else {
pos = {
col: col,
row: row,
size_x: size_x,
size_y: size_y
};
this.empty_cells(col, row, size_x, size_y);
}
var $w = $(html).attr({
'data-col': pos.col,
'data-row': pos.row,
'data-sizex' : size_x,
'data-sizey' : size_y
}).addClass('gs-w').appendTo(this.$el).hide();
this.$widgets = this.$widgets.add($w);
this.register_widget($w);
this.add_faux_rows(pos.size_y);
//this.add_faux_cols(pos.size_x);
if (max_size) {
this.set_widget_max_size($w, max_size);
}
if (min_size) {
this.set_widget_min_size($w, min_size);
}
this.set_dom_grid_width();
this.set_dom_grid_height();
this.drag_api.set_limits(this.cols * this.min_widget_width);
return $w.fadeIn();
};
/**
* Change widget size limits.
*
* @method set_widget_min_size
* @param {HTMLElement|Number} $widget The jQuery wrapped HTMLElement
* representing the widget or an index representing the desired widget.
* @param {Array} min_size Minimum size (in units) for width and height.
* @return {HTMLElement} Returns instance of gridster Class.
*/
fn.set_widget_min_size = function($widget, min_size) {
$widget = typeof $widget === 'number' ?
this.$widgets.eq($widget) : $widget;
if (!$widget.length) { return this; }
var wgd = $widget.data('coords').grid;
wgd.min_size_x = min_size[0];
wgd.min_size_y = min_size[1];
return this;
};
/**
* Change widget size limits.
*
* @method set_widget_max_size
* @param {HTMLElement|Number} $widget The jQuery wrapped HTMLElement
* representing the widget or an index representing the desired widget.
* @param {Array} max_size Maximun size (in units) for width and height.
* @return {HTMLElement} Returns instance of gridster Class.
*/
fn.set_widget_max_size = function($widget, max_size) {
$widget = typeof $widget === 'number' ?
this.$widgets.eq($widget) : $widget;
if (!$widget.length) { return this; }
var wgd = $widget.data('coords').grid;
wgd.max_size_x = max_size[0];
wgd.max_size_y = max_size[1];
return this;
};
/**
* Append the resize handle into a widget.
*
* @method add_resize_handle
* @param {HTMLElement} $widget The jQuery wrapped HTMLElement
* representing the widget.
* @return {HTMLElement} Returns instance of gridster Class.
*/
fn.add_resize_handle = function($w) {
var append_to = this.options.resize.handle_append_to;
$(this.resize_handle_tpl).appendTo( append_to ? $(append_to, $w) : $w);
return this;
};
/**
* Change the size of a widget. Width is limited to the current grid width.
*
* @method resize_widget
* @param {HTMLElement} $widget The jQuery wrapped HTMLElement
* representing the widget.
* @param {Number} size_x The number of columns that will occupy the widget.
* By default <code>size_x</code> is limited to the space available from
* the column where the widget begins, until the last column to the right.
* @param {Number} size_y The number of rows that will occupy the widget.
* @param {Function} [callback] Function executed when the widget is removed.
* @return {HTMLElement} Returns $widget.
*/
fn.resize_widget = function($widget, size_x, size_y, callback) {
var wgd = $widget.coords().grid;
var col = wgd.col;
var max_cols = this.options.max_cols;
var old_size_y = wgd.size_y;
var old_col = wgd.col;
var new_col = old_col;
size_x || (size_x = wgd.size_x);
size_y || (size_y = wgd.size_y);
if (max_cols !== Infinity) {
size_x = Math.min(size_x, max_cols - col + 1);
}
if (size_y > old_size_y) {
this.add_faux_rows(Math.max(size_y - old_size_y, 0));
}
var player_rcol = (col + size_x - 1);
if (player_rcol > this.cols) {
this.add_faux_cols(player_rcol - this.cols);
}
var new_grid_data = {
col: new_col,
row: wgd.row,
size_x: size_x,
size_y: size_y
};
this.mutate_widget_in_gridmap($widget, wgd, new_grid_data);
this.set_dom_grid_height();
this.set_dom_grid_width();
if (callback) {
callback.call(this, new_grid_data.size_x, new_grid_data.size_y);
}
return $widget;
};
/**
* Mutate widget dimensions and position in the grid map.
*
* @method mutate_widget_in_gridmap
* @param {HTMLElement} $widget The jQuery wrapped HTMLElement
* representing the widget to mutate.
* @param {Object} wgd Current widget grid data (col, row, size_x, size_y).
* @param {Object} new_wgd New widget grid data.
* @return {HTMLElement} Returns instance of gridster Class.
*/
fn.mutate_widget_in_gridmap = function($widget, wgd, new_wgd) {
var old_size_x = wgd.size_x;
var old_size_y = wgd.size_y;
var old_cells_occupied = this.get_cells_occupied(wgd);
var new_cells_occupied = this.get_cells_occupied(new_wgd);
var empty_cols = [];
$.each(old_cells_occupied.cols, function(i, col) {
if ($.inArray(col, new_cells_occupied.cols) === -1) {
empty_cols.push(col);
}
});
var occupied_cols = [];
$.each(new_cells_occupied.cols, function(i, col) {
if ($.inArray(col, old_cells_occupied.cols) === -1) {
occupied_cols.push(col);
}
});
var empty_rows = [];
$.each(old_cells_occupied.rows, function(i, row) {
if ($.inArray(row, new_cells_occupied.rows) === -1) {
empty_rows.push(row);
}
});
var occupied_rows = [];
$.each(new_cells_occupied.rows, function(i, row) {
if ($.inArray(row, old_cells_occupied.rows) === -1) {
occupied_rows.push(row);
}
});
this.remove_from_gridmap(wgd);
if (occupied_cols.length) {
var cols_to_empty = [
new_wgd.col, new_wgd.row, new_wgd.size_x, Math.min(old_size_y, new_wgd.size_y), $widget
];
this.empty_cells.apply(this, cols_to_empty);
}
if (occupied_rows.length) {
var rows_to_empty = [new_wgd.col, new_wgd.row, new_wgd.size_x, new_wgd.size_y, $widget];
this.empty_cells.apply(this, rows_to_empty);
}
// not the same that wgd = new_wgd;
wgd.col = new_wgd.col;
wgd.row = new_wgd.row;
wgd.size_x = new_wgd.size_x;
wgd.size_y = new_wgd.size_y;
this.add_to_gridmap(new_wgd, $widget);
$widget.removeClass('player-revert');
//update coords instance attributes
$widget.data('coords').update({
width: (new_wgd.size_x * this.options.widget_base_dimensions[0] +
((new_wgd.size_x - 1) * this.options.widget_margins[0]) * 2),
height: (new_wgd.size_y * this.options.widget_base_dimensions[1] +
((new_wgd.size_y - 1) * this.options.widget_margins[1]) * 2)
});
$widget.attr({
'data-col': new_wgd.col,
'data-row': new_wgd.row,
'data-sizex': new_wgd.size_x,
'data-sizey': new_wgd.size_y
});
if (empty_cols.length) {
var cols_to_remove_holes = [
empty_cols[0], new_wgd.row,
empty_cols.length,
Math.min(old_size_y, new_wgd.size_y),
$widget
];
this.remove_empty_cells.apply(this, cols_to_remove_holes);
}
if (empty_rows.length) {
var rows_to_remove_holes = [
new_wgd.col, new_wgd.row, new_wgd.size_x, new_wgd.size_y, $widget
];
this.remove_empty_cells.apply(this, rows_to_remove_holes);
}
this.move_widget_up($widget);
return this;
};
/**
* Move down widgets in cells represented by the arguments col, row, size_x,
* size_y
*
* @method empty_cells
* @param {Number} col The column where the group of cells begin.
* @param {Number} row The row where the group of cells begin.
* @param {Number} size_x The number of columns that the group of cells
* occupy.
* @param {Number} size_y The number of rows that the group of cells
* occupy.
* @param {HTMLElement} $exclude Exclude widgets from being moved.
* @return {Class} Returns the instance of the Gridster Class.
*/
fn.empty_cells = function(col, row, size_x, size_y, $exclude) {
var $nexts = this.widgets_below({
col: col,
row: row - size_y,
size_x: size_x,
size_y: size_y
});
$nexts.not($exclude).each($.proxy(function(i, w) {
var wgd = $(w).coords().grid;
if ( !(wgd.row <= (row + size_y - 1))) { return; }
var diff = (row + size_y) - wgd.row;
this.move_widget_down($(w), diff);
}, this));
this.set_dom_grid_height();
return this;
};
/**
* Move up widgets below cells represented by the arguments col, row, size_x,
* size_y.
*
* @method remove_empty_cells
* @param {Number} col The column where the group of cells begin.
* @param {Number} row The row where the group of cells begin.
* @param {Number} size_x The number of columns that the group of cells
* occupy.
* @param {Number} size_y The number of rows that the group of cells
* occupy.
* @param {HTMLElement} exclude Exclude widgets from being moved.
* @return {Class} Returns the instance of the Gridster Class.
*/
fn.remove_empty_cells = function(col, row, size_x, size_y, exclude) {
var $nexts = this.widgets_below({
col: col,
row: row,
size_x: size_x,
size_y: size_y
});
$nexts.not(exclude).each($.proxy(function(i, widget) {
this.move_widget_up( $(widget), size_y );
}, this));
this.set_dom_grid_height();
return this;
};
/**
* Get the most left column below to add a new widget.
*
* @method next_position
* @param {Number} size_x The nº of rows the widget occupies horizontally.
* @param {Number} size_y The nº of columns the widget occupies vertically.
* @return {Object} Returns a grid coords object representing the future
* widget coords.
*/
fn.next_position = function(size_x, size_y) {
size_x || (size_x = 1);
size_y || (size_y = 1);
var ga = this.gridmap;
var cols_l = ga.length;
var valid_pos = [];
var rows_l;
for (var c = 1; c < cols_l; c++) {
rows_l = ga[c].length;
for (var r = 1; r <= rows_l; r++) {
var can_move_to = this.can_move_to({
size_x: size_x,
size_y: size_y
}, c, r);
if (can_move_to) {
valid_pos.push({
col: c,
row: r,
size_y: size_y,
size_x: size_x
});
}
}
}
if (valid_pos.length) {
return Gridster.sort_by_row_and_col_asc(valid_pos)[0];
}
return false;
};
/**
* Remove a widget from the grid.
*
* @method remove_widget
* @param {HTMLElement} el The jQuery wrapped HTMLElement you want to remove.
* @param {Boolean|Function} silent If true, widgets below the removed one
* will not move up. If a Function is passed it will be used as callback.
* @param {Function} callback Function executed when the widget is removed.
* @return {Class} Returns the instance of the Grids