/
split.js
612 lines (516 loc) · 24.2 KB
/
split.js
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/*! Split.js - v1.5.3 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Split = factory());
}(this, (function () { 'use strict';
// The programming goals of Split.js are to deliver readable, understandable and
// maintainable code, while at the same time manually optimizing for tiny minified file size,
// browser compatibility without additional requirements, graceful fallback (IE8 is supported)
// and very few assumptions about the user's page layout.
var global = window;
var document = global.document;
// Save a couple long function names that are used frequently.
// This optimization saves around 400 bytes.
var addEventListener = 'addEventListener';
var removeEventListener = 'removeEventListener';
var getBoundingClientRect = 'getBoundingClientRect';
var gutterStartDragging = '_a';
var aGutterSize = '_b';
var bGutterSize = '_c';
var HORIZONTAL = 'horizontal';
var NOOP = function () { return false; };
// Figure out if we're in IE8 or not. IE8 will still render correctly,
// but will be static instead of draggable.
var isIE8 = global.attachEvent && !global[addEventListener];
// Helper function determines which prefixes of CSS calc we need.
// We only need to do this once on startup, when this anonymous function is called.
//
// Tests -webkit, -moz and -o prefixes. Modified from StackOverflow:
// http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167
var calc = (['', '-webkit-', '-moz-', '-o-'].filter(function (prefix) {
var el = document.createElement('div');
el.style.cssText = "width:" + prefix + "calc(9px)";
return (!!el.style.length)
}).shift()) + "calc";
// Helper function checks if its argument is a string-like type
var isString = function (v) { return (typeof v === 'string' || v instanceof String); };
// Helper function allows elements and string selectors to be used
// interchangeably. In either case an element is returned. This allows us to
// do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`.
var elementOrSelector = function (el) {
if (isString(el)) {
var ele = document.querySelector(el);
if (!ele) {
throw new Error(("Selector " + el + " did match a DOM element"))
}
return ele
}
return el
};
// Helper function gets a property from the properties object, with a default fallback
var getOption = function (options, propName, def) {
var value = options[propName];
if (value !== undefined) {
return value
}
return def
};
var getGutterSize = function (gutterSize, isFirst, isLast, gutterAlign) {
if (isFirst) {
if (gutterAlign === 'end') {
return 0
} else if (gutterAlign === 'center') {
return gutterSize / 2
}
} else if (isLast) {
if (gutterAlign === 'start') {
return 0
} else if (gutterAlign === 'center') {
return gutterSize / 2
}
}
return gutterSize
};
// Default options
var defaultGutterFn = function (i, gutterDirection) {
var gut = document.createElement('div');
gut.className = "gutter gutter-" + gutterDirection;
return gut
};
var defaultElementStyleFn = function (dim, size, gutSize) {
var style = {};
if (!isString(size)) {
if (!isIE8) {
style[dim] = calc + "(" + size + "% - " + gutSize + "px)";
} else {
style[dim] = size + "%";
}
} else {
style[dim] = size;
}
return style
};
var defaultGutterStyleFn = function (dim, gutSize) {
var obj;
return (( obj = {}, obj[dim] = (gutSize + "px"), obj ));
};
// The main function to initialize a split. Split.js thinks about each pair
// of elements as an independant pair. Dragging the gutter between two elements
// only changes the dimensions of elements in that pair. This is key to understanding
// how the following functions operate, since each function is bound to a pair.
//
// A pair object is shaped like this:
//
// {
// a: DOM element,
// b: DOM element,
// aMin: Number,
// bMin: Number,
// dragging: Boolean,
// parent: DOM element,
// direction: 'horizontal' | 'vertical'
// }
//
// The basic sequence:
//
// 1. Set defaults to something sane. `options` doesn't have to be passed at all.
// 2. Initialize a bunch of strings based on the direction we're splitting.
// A lot of the behavior in the rest of the library is paramatized down to
// rely on CSS strings and classes.
// 3. Define the dragging helper functions, and a few helpers to go with them.
// 4. Loop through the elements while pairing them off. Every pair gets an
// `pair` object and a gutter.
// 5. Actually size the pair elements, insert gutters and attach event listeners.
var Split = function (idsOption, options) {
if ( options === void 0 ) options = {};
var ids = idsOption;
var dimension;
var clientAxis;
var position;
var elements;
// Allow HTMLCollection to be used as an argument when supported
if (Array.from) {
ids = Array.from(ids);
}
// All DOM elements in the split should have a common parent. We can grab
// the first elements parent and hope users read the docs because the
// behavior will be whacky otherwise.
var firstElement = elementOrSelector(ids[0]);
var parent = firstElement.parentNode;
var parentFlexDirection = global.getComputedStyle(parent).flexDirection;
// Set default options.sizes to equal percentages of the parent element.
var sizes = getOption(options, 'sizes') || ids.map(function () { return 100 / ids.length; });
// Standardize minSize to an array if it isn't already. This allows minSize
// to be passed as a number.
var minSize = getOption(options, 'minSize', 100);
var minSizes = Array.isArray(minSize) ? minSize : ids.map(function () { return minSize; });
// Get other options
var expandToMin = getOption(options, 'expandToMin', false);
var gutterSize = getOption(options, 'gutterSize', 10);
var gutterAlign = getOption(options, 'gutterAlign', 'center');
var snapOffset = getOption(options, 'snapOffset', 30);
var dragInterval = getOption(options, 'dragInterval', 0);
var direction = getOption(options, 'direction', HORIZONTAL);
var cursor = getOption(options, 'cursor', direction === HORIZONTAL ? 'ew-resize' : 'ns-resize');
var gutter = getOption(options, 'gutter', defaultGutterFn);
var elementStyle = getOption(options, 'elementStyle', defaultElementStyleFn);
var gutterStyle = getOption(options, 'gutterStyle', defaultGutterStyleFn);
// 2. Initialize a bunch of strings based on the direction we're splitting.
// A lot of the behavior in the rest of the library is paramatized down to
// rely on CSS strings and classes.
if (direction === HORIZONTAL) {
dimension = 'width';
clientAxis = 'clientX';
position = 'left';
} else if (direction === 'vertical') {
dimension = 'height';
clientAxis = 'clientY';
position = 'top';
}
// 3. Define the dragging helper functions, and a few helpers to go with them.
// Each helper is bound to a pair object that contains its metadata. This
// also makes it easy to store references to listeners that that will be
// added and removed.
//
// Even though there are no other functions contained in them, aliasing
// this to self saves 50 bytes or so since it's used so frequently.
//
// The pair object saves metadata like dragging state, position and
// event listener references.
function setElementSize (el, size, gutSize) {
// Split.js allows setting sizes via numbers (ideally), or if you must,
// by string, like '300px'. This is less than ideal, because it breaks
// the fluid layout that `calc(% - px)` provides. You're on your own if you do that,
// make sure you calculate the gutter size by hand.
var style = elementStyle(dimension, size, gutSize);
// eslint-disable-next-line no-param-reassign
Object.keys(style).forEach(function (prop) {
el.style[prop] = style[prop];
});
}
function setGutterSize (gutterElement, gutSize) {
var style = gutterStyle(dimension, gutSize);
// eslint-disable-next-line no-param-reassign
Object.keys(style).forEach(function (prop) {
gutterElement.style[prop] = style[prop];
});
}
function getSizes () {
return elements.map(function (element) { return element.size; })
}
// Actually adjust the size of elements `a` and `b` to `offset` while dragging.
// calc is used to allow calc(percentage + gutterpx) on the whole split instance,
// which allows the viewport to be resized without additional logic.
// Element a's size is the same as offset. b's size is total size - a size.
// Both sizes are calculated from the initial parent percentage,
// then the gutter size is subtracted.
function adjust (offset) {
var a = elements[this.a];
var b = elements[this.b];
var percentage = a.size + b.size;
a.size = (offset / this.size) * percentage;
b.size = (percentage - ((offset / this.size) * percentage));
setElementSize(a.element, a.size, this[aGutterSize]);
setElementSize(b.element, b.size, this[bGutterSize]);
}
// drag, where all the magic happens. The logic is really quite simple:
//
// 1. Ignore if the pair is not dragging.
// 2. Get the offset of the event.
// 3. Snap offset to min if within snappable range (within min + snapOffset).
// 4. Actually adjust each element in the pair to offset.
//
// ---------------------------------------------------------------------
// | | <- a.minSize || b.minSize -> | |
// | | | <- this.snapOffset || this.snapOffset -> | | |
// | | | || | | |
// | | | || | | |
// ---------------------------------------------------------------------
// | <- this.start this.size -> |
function drag (e) {
var offset;
var a = elements[this.a];
var b = elements[this.b];
if (!this.dragging) { return }
// Get the offset of the event from the first side of the
// pair `this.start`. Supports touch events, but not multitouch, so only the first
// finger `touches[0]` is counted.
if ('touches' in e) {
offset = e.touches[0][clientAxis] - this.start;
} else {
offset = e[clientAxis] - this.start;
}
if (dragInterval > 0) {
offset = Math.round(offset / dragInterval) * dragInterval;
}
// if (gutterAlign === 'start') {
// offset -= this[aGutterSize]
// } else if (gutterAlign === 'end') {
// offset += this[bGutterSize]
// }
// If within snapOffset of min or max, set offset to min or max.
// snapOffset buffers a.minSize and b.minSize, so logic is opposite for both.
// Include the appropriate gutter sizes to prevent overflows.
if (offset <= a.minSize + snapOffset + this[aGutterSize]) {
offset = a.minSize + this[aGutterSize];
} else if (offset >= this.size - (b.minSize + snapOffset + this[bGutterSize])) {
offset = this.size - (b.minSize + this[bGutterSize]);
}
// Actually adjust the size.
adjust.call(this, offset);
// Call the drag callback continously. Don't do anything too intensive
// in this callback.
getOption(options, 'onDrag', NOOP)();
}
// Cache some important sizes when drag starts, so we don't have to do that
// continously:
//
// `size`: The total size of the pair. First + second + first gutter + second gutter.
// `start`: The leading side of the first element.
//
// ------------------------------------------------
// | aGutterSize -> ||| |
// | ||| |
// | ||| |
// | ||| <- bGutterSize |
// ------------------------------------------------
// | <- start size -> |
function calculateSizes () {
// Figure out the parent size minus padding.
var a = elements[this.a].element;
var b = elements[this.b].element;
var aBounds = a[getBoundingClientRect]();
var bBounds = b[getBoundingClientRect]();
this.size = aBounds[dimension] + bBounds[dimension] + this[aGutterSize] + this[bGutterSize];
this.start = aBounds[position];
}
// stopDragging is very similar to startDragging in reverse.
function stopDragging () {
var self = this;
var a = elements[self.a].element;
var b = elements[self.b].element;
if (self.dragging) {
getOption(options, 'onDragEnd', NOOP)(getSizes());
}
self.dragging = false;
// Remove the stored event listeners. This is why we store them.
global[removeEventListener]('mouseup', self.stop);
global[removeEventListener]('touchend', self.stop);
global[removeEventListener]('touchcancel', self.stop);
global[removeEventListener]('mousemove', self.move);
global[removeEventListener]('touchmove', self.move);
// Clear bound function references
self.stop = null;
self.move = null;
a[removeEventListener]('selectstart', NOOP);
a[removeEventListener]('dragstart', NOOP);
b[removeEventListener]('selectstart', NOOP);
b[removeEventListener]('dragstart', NOOP);
a.style.userSelect = '';
a.style.webkitUserSelect = '';
a.style.MozUserSelect = '';
a.style.pointerEvents = '';
b.style.userSelect = '';
b.style.webkitUserSelect = '';
b.style.MozUserSelect = '';
b.style.pointerEvents = '';
self.gutter.style.cursor = '';
self.parent.style.cursor = '';
document.body.style.cursor = '';
}
// startDragging calls `calculateSizes` to store the inital size in the pair object.
// It also adds event listeners for mouse/touch events,
// and prevents selection while dragging so avoid the selecting text.
function startDragging (e) {
// Right-clicking can't start dragging.
if (e.button !== 0) {
return
}
// Alias frequently used variables to save space. 200 bytes.
var self = this;
var a = elements[self.a].element;
var b = elements[self.b].element;
// Call the onDragStart callback.
if (!self.dragging) {
getOption(options, 'onDragStart', NOOP)(getSizes());
}
// Don't actually drag the element. We emulate that in the drag function.
e.preventDefault();
// Set the dragging property of the pair object.
self.dragging = true;
// Create two event listeners bound to the same pair object and store
// them in the pair object.
self.move = drag.bind(self);
self.stop = stopDragging.bind(self);
// All the binding. `window` gets the stop events in case we drag out of the elements.
global[addEventListener]('mouseup', self.stop);
global[addEventListener]('touchend', self.stop);
global[addEventListener]('touchcancel', self.stop);
global[addEventListener]('mousemove', self.move);
global[addEventListener]('touchmove', self.move);
// Disable selection. Disable!
a[addEventListener]('selectstart', NOOP);
a[addEventListener]('dragstart', NOOP);
b[addEventListener]('selectstart', NOOP);
b[addEventListener]('dragstart', NOOP);
a.style.userSelect = 'none';
a.style.webkitUserSelect = 'none';
a.style.MozUserSelect = 'none';
a.style.pointerEvents = 'none';
b.style.userSelect = 'none';
b.style.webkitUserSelect = 'none';
b.style.MozUserSelect = 'none';
b.style.pointerEvents = 'none';
// Set the cursor at multiple levels
self.gutter.style.cursor = cursor;
self.parent.style.cursor = cursor;
document.body.style.cursor = cursor;
// Cache the initial sizes of the pair.
calculateSizes.call(self);
}
// 5. Create pair and element objects. Each pair has an index reference to
// elements `a` and `b` of the pair (first and second elements).
// Loop through the elements while pairing them off. Every pair gets a
// `pair` object and a gutter.
//
// Basic logic:
//
// - Starting with the second element `i > 0`, create `pair` objects with
// `a = i - 1` and `b = i`
// - Set gutter sizes based on the _pair_ being first/last. The first and last
// pair have gutterSize / 2, since they only have one half gutter, and not two.
// - Create gutter elements and add event listeners.
// - Set the size of the elements, minus the gutter sizes.
//
// -----------------------------------------------------------------------
// | i=0 | i=1 | i=2 | i=3 |
// | | | | |
// | pair 0 pair 1 pair 2 |
// | | | | |
// -----------------------------------------------------------------------
var pairs = [];
elements = ids.map(function (id, i) {
// Create the element object.
var element = {
element: elementOrSelector(id),
size: sizes[i],
minSize: minSizes[i],
i: i,
};
var pair;
if (i > 0) {
// Create the pair object with its metadata.
pair = {
a: i - 1,
b: i,
dragging: false,
direction: direction,
parent: parent,
};
pair[aGutterSize] = getGutterSize(gutterSize, i - 1 === 0, false, gutterAlign);
pair[bGutterSize] = getGutterSize(gutterSize, false, i === ids.length - 1, gutterAlign);
// if the parent has a reverse flex-direction, switch the pair elements.
if (parentFlexDirection === 'row-reverse' || parentFlexDirection === 'column-reverse') {
var temp = pair.a;
pair.a = pair.b;
pair.b = temp;
}
}
// Determine the size of the current element. IE8 is supported by
// staticly assigning sizes without draggable gutters. Assigns a string
// to `size`.
//
// IE9 and above
if (!isIE8) {
// Create gutter elements for each pair.
if (i > 0) {
var gutterElement = gutter(i, direction, element.element);
setGutterSize(gutterElement, gutterSize);
// Save bound event listener for removal later
pair[gutterStartDragging] = startDragging.bind(pair);
// Attach bound event listener
gutterElement[addEventListener]('mousedown', pair[gutterStartDragging]);
gutterElement[addEventListener]('touchstart', pair[gutterStartDragging]);
parent.insertBefore(gutterElement, element.element);
pair.gutter = gutterElement;
}
}
setElementSize(
element.element,
element.size,
getGutterSize(gutterSize, i === 0, i === ids.length - 1, gutterAlign)
);
// After the first iteration, and we have a pair object, append it to the
// list of pairs.
if (i > 0) {
pairs.push(pair);
}
return element
});
function adjustToMin (element) {
var isLast = (element.i === pairs.length);
var pair = isLast ? pairs[element.i - 1] : pairs[element.i];
calculateSizes.call(pair);
var size = isLast ? (pair.size - element.minSize - pair[bGutterSize]) : element.minSize + pair[aGutterSize];
adjust.call(pair, size);
}
elements.forEach(function (element) {
var computedSize = element.element[getBoundingClientRect]()[dimension];
if (computedSize < element.minSize) {
if (expandToMin) {
adjustToMin(element);
} else {
element.minSize = computedSize;
}
}
});
function setSizes (newSizes) {
newSizes.forEach(function (newSize, i) {
if (i > 0) {
var pair = pairs[i - 1];
var a = elements[pair.a];
var b = elements[pair.b];
a.size = newSizes[i - 1];
b.size = newSize;
setElementSize(a.element, a.size, pair[aGutterSize]);
setElementSize(b.element, b.size, pair[bGutterSize]);
}
});
}
function destroy (preserveStyles, preserveGutter) {
pairs.forEach(function (pair) {
if (preserveGutter !== true) {
pair.parent.removeChild(pair.gutter);
} else {
pair.gutter[removeEventListener]('mousedown', pair[gutterStartDragging]);
pair.gutter[removeEventListener]('touchstart', pair[gutterStartDragging]);
}
if (preserveStyles !== true) {
var style = elementStyle(dimension, pair.a.size, pair[aGutterSize]);
Object.keys(style).forEach(function (prop) {
elements[pair.a].element.style[prop] = '';
elements[pair.b].element.style[prop] = '';
});
}
});
}
if (isIE8) {
return {
setSizes: setSizes,
destroy: destroy,
}
}
return {
setSizes: setSizes,
getSizes: getSizes,
collapse: function collapse (i) {
adjustToMin(elements[i]);
},
destroy: destroy,
parent: parent,
pairs: pairs,
}
};
return Split;
})));