Repository navigation
Expand file tree
/
Copy pathjquery.gridList.js
More file actions
327 lines (284 loc) · 9.94 KB
/
Copy pathjquery.gridList.js
File metadata and controls
327 lines (284 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// It does not try to register in a CommonJS environment since jQuery is not
// likely to run in those environments.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'gridlist'], factory);
} else {
factory(jQuery, GridList);
}
}(function($, GridList) {
var DraggableGridList = function(element, options) {
this.options = $.extend({}, this.defaults, options);
this.$element = $(element);
this._init();
this._bindEvents();
};
DraggableGridList.prototype = {
defaults: {
rows: 5,
widthHeightRatio: 1,
dragAndDrop: true
},
destroy: function() {
this._unbindEvents();
},
resize: function(rows) {
if (rows) {
this.options.rows = rows;
}
this._createGridSnapshot();
this.gridList.resizeGrid(this.options.rows);
this._updateGridSnapshot();
this.reflow();
},
resizeItem: function(element, size) {
this._createGridSnapshot();
this.gridList.resizeItem(this._getItemByElement(element), size);
this._updateGridSnapshot();
this.render();
},
reflow: function() {
this._calculateCellSize();
this.render();
},
render: function() {
this._applySizeToItems();
this._applyPositionToItems();
},
_bindMethod: function(fn) {
/**
* Bind prototype method to instance scope (similar to CoffeeScript's fat
* arrow)
*/
var that = this;
return function() {
return fn.apply(that, arguments);
};
},
_init: function() {
// Read items and their meta data. Ignore other list elements (like the
// position highlight)
this.$items = this.$element.children('li[data-w]');
this.items = this._generateItemsFromDOM();
// Used to highlight a position an element will land on upon drop
this.$positionHighlight = this.$element.find('.position-highlight').hide();
this._initGridList();
this.reflow();
if (this.options.dragAndDrop) {
// Init Draggable JQuery UI plugin for each of the list items
// http://api.jqueryui.com/draggable/
this.$items.draggable({
zIndex: this.items.length,
scroll: false
});
}
},
_initGridList: function() {
// Create instance of GridList (decoupled lib for handling the grid
// positioning and sorting post-drag and dropping)
this.gridList = new GridList(this.items, {rows: this.options.rows});
},
_bindEvents: function() {
this._onStart = this._bindMethod(this._onStart);
this._onDrag = this._bindMethod(this._onDrag);
this._onStop = this._bindMethod(this._onStop);
this.$items.on('dragstart', this._onStart);
this.$items.on('drag', this._onDrag);
this.$items.on('dragstop', this._onStop);
},
_unbindEvents: function() {
this.$items.off('dragstart', this._onStart);
this.$items.off('drag', this._onDrag);
this.$items.off('dragstop', this._onStop);
},
_onStart: function(event, ui) {
// Create a deep copy of the items; we use them to revert the item
// positions after each drag change, making an entire drag operation less
// distructable
this._createGridSnapshot();
// Since dragging actually alters the grid, we need to establish the number
// of cols (+1 extra) before the drag starts
this._maxGridCols = this.gridList.grid.length;
},
_onDrag: function(event, ui) {
var item = this._getItemByElement(ui.helper),
newPosition = this._snapItemPositionToGrid(item);
if (this._dragPositionChanged(newPosition)) {
this._previousDragPosition = newPosition;
// Regenerate the grid with the positions from when the drag started
GridList.cloneItems(this._items, this.items);
this.gridList.generateGrid();
// Since the items list is a deep copy, we need to fetch the item
// corresponding to this drag action again
item = this._getItemByElement(ui.helper);
this.gridList.moveItemToPosition(item, newPosition);
// Visually update item positions and highlight shape
this._applyPositionToItems();
this._highlightPositionForItem(item);
}
},
_onStop: function(event, ui) {
this._updateGridSnapshot();
this._previousDragPosition = null;
// HACK: jQuery.draggable removes this class after the dragstop callback,
// and we need it removed before the drop, to re-enable CSS transitions
$(ui.helper).removeClass('ui-draggable-dragging');
this._applyPositionToItems();
this._removePositionHighlight();
},
_generateItemsFromDOM: function() {
/**
* Generate the structure of items used by the GridList lib, using the DOM
* data of the children of the targeted element. The items will have an
* additional reference to the initial DOM element attached, in order to
* trace back to it and re-render it once its properties are changed by the
* GridList lib
*/
var _this = this,
items = [],
item;
this.$items.each(function(i, element) {
items.push({
$element: $(element),
x: Number($(element).attr('data-x')),
y: Number($(element).attr('data-y')),
w: Number($(element).attr('data-w')),
h: Number($(element).attr('data-h')),
id: Number($(element).attr('data-id'))
});
});
return items;
},
_getItemByElement: function(element) {
// XXX: this could be optimized by storing the item reference inside the
// meta data of the DOM element
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].$element.is(element)) {
return this.items[i];
}
}
},
_calculateCellSize: function() {
this._cellHeight = Math.floor(this.$element.height() / this.options.rows);
this._cellWidth = this._cellHeight * this.options.widthHeightRatio;
if (this.options.heightToFontSizeRatio) {
this._fontSize = this._cellHeight * this.options.heightToFontSizeRatio;
}
},
_getItemWidth: function(item) {
return item.w * this._cellWidth;
},
_getItemHeight: function(item) {
return item.h * this._cellHeight;
},
_applySizeToItems: function() {
for (var i = 0; i < this.items.length; i++) {
this.items[i].$element.css({
width: this._getItemWidth(this.items[i]),
height: this._getItemHeight(this.items[i])
});
}
if (this.options.heightToFontSizeRatio) {
this.$items.css('font-size', this._fontSize);
}
},
_applyPositionToItems: function() {
// TODO: Implement group separators
for (var i = 0; i < this.items.length; i++) {
// Don't interfere with the positions of the dragged items
if (this.items[i].move) {
continue;
}
this.items[i].$element.css({
left: this.items[i].x * this._cellWidth,
top: this.items[i].y * this._cellHeight
});
}
// Update the width of the entire grid container with an extra column on
// the right for extra dragging room
this.$element.width((this.gridList.grid.length + 1) * this._cellWidth);
},
_dragPositionChanged: function(newPosition) {
if (!this._previousDragPosition) {
return true;
}
return (newPosition[0] != this._previousDragPosition[0] ||
newPosition[1] != this._previousDragPosition[1]);
},
_snapItemPositionToGrid: function(item) {
var position = item.$element.position(),
row,
col;
position[0] -= this.$element.position().left;
col = Math.round(position.left / this._cellWidth);
row = Math.round(position.top / this._cellHeight);
// Keep item position within the grid and don't let the item create more
// than one extra column
col = Math.max(col, 0);
row = Math.max(row, 0);
col = Math.min(col, this._maxGridCols);
row = Math.min(row, this.options.rows - item.h);
return [col, row];
},
_highlightPositionForItem: function(item) {
this.$positionHighlight.css({
width: this._getItemWidth(item),
height: this._getItemHeight(item),
left: item.x * this._cellWidth,
top: item.y * this._cellHeight
}).show();
if (this.options.heightToFontSizeRatio) {
this.$positionHighlight.css('font-size', this._fontSize);
}
},
_removePositionHighlight: function() {
this.$positionHighlight.hide();
},
_createGridSnapshot: function() {
this._items = GridList.cloneItems(this.items);
},
_updateGridSnapshot: function() {
// Notify the user with the items that changed since the previous snapshot
this._triggerOnChange();
GridList.cloneItems(this.items, this._items);
},
_triggerOnChange: function() {
if (typeof(this.options.onChange) != 'function') {
return;
}
this.options.onChange.call(
this, this.gridList.getChangedItems(this._items, '$element'));
}
};
$.fn.gridList = function(options) {
if (!window.GridList) {
throw new Error('GridList lib required');
}
var instance,
method,
args;
if (typeof(options) == 'string') {
method = options;
args = Array.prototype.slice.call(arguments, 1);
}
this.each(function() {
instance = $(this).data('_gridList');
// The plugin call be called with no method on an existing GridList
// instance to re-initialize it
if (instance && !method) {
instance.destroy();
instance = null;
}
if (!instance) {
instance = new DraggableGridList(this, options);
$(this).data('_gridList', instance);
}
if (method) {
instance[method].apply(instance, args);
}
});
// Maintain jQuery chain
return this;
};
}));