-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinpacking.js
More file actions
424 lines (369 loc) · 14.8 KB
/
Copy pathbinpacking.js
File metadata and controls
424 lines (369 loc) · 14.8 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
(function ($, undefined) {
/* binpacking.js (aka massive-octo-batman, as recommended by GitHub)
Configuration options: see 'settings' variable. // further reading:
// http://jmlr.org/papers/volume11/gyorgy10a/gyorgy10a.pdf
// http://i11www.iti.uni-karlsruhe.de/_media/teaching/sommer2010/approximationsonlinealgorithmen/onl-bp.pdf
Willet Inc. claims copyright to all remaining portions of this code,
licensing them under hybrid BSD and MIT licenses.
*/
"use strict";
var defaults = {
after: undefined, // for locating the element after which thigns are appended
bindResize: undefined,
debug: false,
target: '.bin',
easing: 'easeOutQuint',
columnWidth: 0,
objects: [], // for things like 'append'
animationDuration: 600,
resizeFrequency: 1000
}, $window = $(window);
function getCoords(input, includeMargins) {
// @param input: either a left/right/top/bottom/... object,
// or a jquery element.
// failed calculations will give you NaN.
// TODO: short circuit applies to 0
includeMargins = includeMargins || false; // can't default to true
if (input.jquery) { // this is $(element)
input = {
left: input.offset().left,
top: input.offset().top,
width: input.outerWidth(includeMargins),
height: input.outerHeight(includeMargins)
};
}
return {
left: input.left || (input.right - input.width),
top: input.top || (input.bottom - input.height),
width: input.width || (input.right - input.left),
height: input.height || (input.bottom - input.top),
bottom: (input.top + input.height) || input.bottom,
right: (input.left + input.width) || input.right
};
}
function each(obj, iterator, context) {
// mod of _.each
// github.com/jashkenas/underscore/blob/1.5.1/underscore.js#L76
// underscore.js (or its portions) is licensed under MIT.
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and
// Investigative Reporters & Editors
var i, l, objKey;
if (obj === null) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (i = 0, l = obj.length; i < l; i++) {
iterator.call(context, obj[i], i, obj);
}
} else {
for (objKey in obj) {
if (obj.hasOwnProperty(objKey)) {
iterator.call(context, obj[objKey], objKey, obj);
}
}
}
}
function sum() {
// really, JS?
// mod of www.codingforums.com/showthread.php?t=218803
var args = Array.prototype.slice.call(arguments, 0);
return args.reduce(function (a, b) {
return a + b;
});
}
function closestNum(target) {
// target, [numbers, ...]. returns the number closest to target.
var nums = {},
diff = Infinity,
diffs = [],
i;
for (i = 1; i < arguments.length; i++) {
diff = Math.abs(target - arguments[i]);
diffs.push(diff);
nums[diff] = arguments[i];
}
return nums[Math.min.apply(null, diffs)];
}
function throttle(func, wait, options) {
// mod of _.throttle
//github.com/jashkenas/underscore/blob/1.5.1/underscore.js#L648
options = options || {};
var context, args, result,
timeout = null,
previous = 0,
later = function () {
previous = options.leading === false ? 0 : new Date();
timeout = null;
result = func.apply(context, args);
};
return function () {
var now = new Date(),
remaining;
if (!previous && options.leading === false) previous = now;
remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
function $pluck($objList, attrib, method) {
// like _.pluck, but on a list of objects.
// you can also do $pluck($('.bin'), true, 'outerHeight')
return $objList.map(function (idx, obj) {
return $(obj)[method || 'prop'](attrib);
});
}
function relayoutInstance($element) {
var instance = $element.data('binpackInstance');
if (instance) {
console.log('resize');
instance.layout();
}
}
function objInit(params) {
// handles $().binpack({ object })
// (add target class to each element)
var binPacker, $hosts = this, settings;
function initSettings(newSettings, prefix) {
// if you give in newSettings, newSettings becomes the new settings.
// returns settings, old or new.
prefix = prefix || 'binpack';
var settingsKey = prefix + 'Settings',
_settings = $.extend({}, defaults, newSettings);
if (newSettings) { // set
$hosts.data(settingsKey, _settings);
} else { // get
_settings = $hosts.data(settingsKey);
if (!_settings) {
// save settings for other calling methods
_settings = $.extend({}, defaults, newSettings);
$hosts.data(settingsKey, _settings);
}
newSettings = _settings;
}
return newSettings;
}
return $hosts.each(function (i, host) { // chaining
var $host = $(host), _resize;
settings = initSettings(params);
binPacker = new BinPack(settings);
binPacker.$container = $host;
binPacker.layout();
// events go here
// TODO: isolate if needed
(function attachEvents() {
_resize = throttle(function () {
if ($window.width() !== $window.data('binpack-width')) {
relayoutInstance($host);
$window.data('binpack-width', $window.width());
}
}, settings.resizeFrequency);
if (settings.bindResize === true) {
$window.resize(_resize);
}
}());
// jQuery-bound data object keeps reference of this instance
$host.data('binpackInstance', binPacker);
});
}
function arrayInit($elements, after) {
// handles $().binpack([ elements ], [after=undefined])
// (appends target class to each element)
var $host = this,
targetElement;
if (after) {
targetElement = after; // well you specified it
$elements.insertAfter(targetElement);
} else { // put at the end
$host.append($elements);
}
return objInit.apply($host);
}
// ========================================================================
function BinPack(settings) {
// definition of a BinPack "job"
this.settings = settings;
this.$container = null;
this.columns = {};
}
BinPack.prototype.getColumnWidth = function () {
// TODO: dynamic callable width (typeof === 'function')
if (this.settings.columnWidth) {
return this.settings.columnWidth;
} else {
// if column width is not specified, use the width of the first item
var firstItem = $(this.settings.target, this.$container).eq(0);
// not sure if modify...
this.settings.columnWidth = firstItem.outerWidth(true);
return this.settings.columnWidth;
}
};
BinPack.prototype.getNumColumns = function () {
// calculate the number of columns
return Math.floor(this.$container.innerWidth() / this.getColumnWidth());
};
BinPack.prototype.getColumns = function () {
return this.initColumns(this.getNumColumns());
};
BinPack.prototype.getShortestColumn = function () {
var columns = this.getColumns(),
shortestColumn = 0,
shortestColumnHeight = Infinity;
$.map(columns, function (val, key) {
if (val.height < shortestColumnHeight) {
shortestColumn = key;
shortestColumnHeight = val.height;
}
});
return columns[shortestColumn];
};
BinPack.prototype.getTallestColumn = function () {
var columns = this.getColumns(),
tallestColumn = 0,
tallestColumnHeight = 0;
$.map(columns, function (val, key) {
if (val.height > tallestColumnHeight) {
tallestColumn = key;
tallestColumnHeight = val.height;
}
});
return columns[tallestColumn];
};
BinPack.prototype.initColumns = function (columnCount, force) {
// this runs only once.
if (this.columns && this.columns[0]) {
// properly initialised columns should have column #0.
if (!force) {
return this.columns;
}
}
this.columns = {};
for (var i = 0; i < columnCount; i++) {
this.columns[i] = {
'index': i,
'contents': [],
'width': this.settings.columnWidth,
'height': 0
};
}
return this.columns;
};
BinPack.prototype.addBinToColumn = function (columnId, $bin) {
// @return: {columnId:
// { contents: [bin, bin, bin],
// width: 1234
// height: 1234
// },
// columnId: ...
// }
try {
this.columns[columnId].contents.push($bin);
} catch (err) {
this.columns[columnId].contents = [$bin];
}
var blockWidths = $(this.columns[columnId].contents).map(function (i, o) {
return $(o).outerWidth(true);
});
var blockHeights = $(this.columns[columnId].contents).map(function (i, o) {
return $(o).outerHeight(true);
});
this.columns[columnId].width = Math.max.apply(null, blockWidths);
this.columns[columnId].height = sum.apply(null, blockHeights);
return this.columns;
};
BinPack.prototype.moveBlock = function ($bin, x, y) {
// move with css
if ($.support.transition) { //api.jquery.com/jQuery.support/
$bin.css({
left: x,
top: y,
// http://matthewlein.com/ceaser/
'transition': 'all ' + this.settings.animationDuration +
'ms cubic-bezier(0.230, 1.000, 0.320, 1.000)',
'transition-timing-function': 'cubic-bezier(0.165, 0.840, 0.440, 1.000)'
});
} else { // jquery fallback
$bin.animate({
left: x,
top: y
}, this.settings.animationDuration, this.settings.easing);
}
};
BinPack.prototype.layout = function () {
// guess what this does
var instance = this, // this is a JS variable
$container = instance.$container, // this is the $(DOM element)
settings = instance.settings,
$blocks = $(settings.target, $container), // blocks
numColumns = instance.getNumColumns(),
hostCoords = getCoords($container),
centeringOffset = (hostCoords.width - numColumns * instance.getColumnWidth()) / 2;
// this is necessary
$container.css('position', 'relative');
$blocks.each(function (idx, block) {
var $block = $(block),
newStyles = {},
shortestColumn = instance.getShortestColumn();
newStyles.left = centeringOffset +
(shortestColumn.width ||
settings.columnWidth ||
(hostCoords.width - centeringOffset * 2) / settings.columns)
* shortestColumn.index;
newStyles.top = shortestColumn.height;
$block.css({position: 'absolute'}).stop(); // keep moving elements in place
instance.moveBlock($block, newStyles.left, newStyles.top);
// recalculate width/height
instance.addBinToColumn(shortestColumn.index, $block);
});
// pretend the container is actually containing the absolute stuff
$container.height(instance.getTallestColumn().height);
// reset geometry data so resizing works
instance.initColumns(numColumns, true);
};
// ========================================================================
// add the animation
if (!$.easing.easeOutQuint) {
$.easing.easeOutQuint = function (x, t, b, c, d) {
// jquery.easing.easeOutQuint
// gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js
// jquery.easing.1.3.js is licensed under BSD.
// Copyright © 2008 George McGinley Smith
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
};
}
$.fn.binpack = function (params) {
// this is a $(DOM element of the container)
if (params instanceof Array) { // [], but not {}
return arrayInit.apply(this, arguments);
} else if (params instanceof Object) { // [] and {}, but [] already got picked out by previous if statement
return objInit.apply(this, arguments);
} else if (typeof params === 'string' && arguments.length >= 2) { // i.e. $.binpack('method', somethingElse)
switch (params) {
case 'append':
return arrayInit.apply(this, arguments);
case 'layout':
return this.data('binpackInstance').layout();
default:
// pass
}
}
// you did something really stupid
throw ('Unsupported calling method!');
};
(function (mediator) {
// hooks
if (mediator) {
mediator.on('layout', relayoutInstance);
}
}(window.Willet && window.Willet.mediator));
}(jQuery));