split.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // The programming goals of Split.js are to deliver readable, understandable and
  2. // maintainable code, while at the same time manually optimizing for tiny minified file size,
  3. // browser compatibility without additional requirements, graceful fallback (IE8 is supported)
  4. // and very few assumptions about the user's page layout.
  5. //
  6. // Make sure all browsers handle this JS library correctly with ES5.
  7. // More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
  8. 'use strict';
  9. // A wrapper function that does a couple things:
  10. //
  11. // 1. Doesn't pollute the global namespace. This is important for a library.
  12. // 2. Allows us to mount the library in different module systems, as well as
  13. // directly in the browser.
  14. (function() {
  15. // Save the global `this` for use later. In this case, since the library only
  16. // runs in the browser, it will refer to `window`. Also, figure out if we're in IE8
  17. // or not. IE8 will still render correctly, but will be static instead of draggable.
  18. //
  19. // Save a couple long function names that are used frequently.
  20. // This optimization saves around 400 bytes.
  21. var global = this
  22. , isIE8 = global.attachEvent && !global[addEventListener]
  23. , document = global.document
  24. , addEventListener = 'addEventListener'
  25. , removeEventListener = 'removeEventListener'
  26. , getBoundingClientRect = 'getBoundingClientRect'
  27. // This library only needs two helper functions:
  28. //
  29. // The first determines which prefixes of CSS calc we need.
  30. // We only need to do this once on startup, when this anonymous function is called.
  31. //
  32. // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow:
  33. // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167
  34. , calc = (function () {
  35. var el
  36. , prefixes = ["", "-webkit-", "-moz-", "-o-"]
  37. for (var i = 0; i < prefixes.length; i++) {
  38. el = document.createElement('div')
  39. el.style.cssText = "width:" + prefixes[i] + "calc(9px)"
  40. if (el.style.length) {
  41. return prefixes[i] + "calc"
  42. }
  43. }
  44. })()
  45. // The second helper function allows elements and string selectors to be used
  46. // interchangeably. In either case an element is returned. This allows us to
  47. // do `Split(elem1, elem2)` as well as `Split('#id1', '#id2')`.
  48. , elementOrSelector = function (el) {
  49. if (typeof el === 'string' || el instanceof String) {
  50. return document.querySelector(el)
  51. } else {
  52. return el
  53. }
  54. }
  55. // The main function to initialize a split. Split.js thinks about each pair
  56. // of elements as an independant pair. Dragging the gutter between two elements
  57. // only changes the dimensions of elements in that pair. This is key to understanding
  58. // how the following functions operate, since each function is bound to a pair.
  59. //
  60. // A pair object is shaped like this:
  61. //
  62. // {
  63. // a: DOM element,
  64. // b: DOM element,
  65. // aMin: Number,
  66. // bMin: Number,
  67. // dragging: Boolean,
  68. // parent: DOM element,
  69. // isFirst: Boolean,
  70. // isLast: Boolean,
  71. // direction: 'horizontal' | 'vertical'
  72. // }
  73. //
  74. // The basic sequence:
  75. //
  76. // 1. Set defaults to something sane. `options` doesn't have to be passed at all.
  77. // 2. Initialize a bunch of strings based on the direction we're splitting.
  78. // A lot of the behavior in the rest of the library is paramatized down to
  79. // rely on CSS strings and classes.
  80. // 3. Define the dragging helper functions, and a few helpers to go with them.
  81. // 4. Define a few more functions that "balance" the entire split instance.
  82. // Split.js tries it's best to cope with min sizes that don't add up.
  83. // 5. Loop through the elements while pairing them off. Every pair gets an
  84. // `pair` object, a gutter, and special isFirst/isLast properties.
  85. // 6. Actually size the pair elements, insert gutters and attach event listeners.
  86. // 7. Balance all of the pairs to accomodate min sizes as best as possible.
  87. , Split = function (ids, options) {
  88. var dimension
  89. , i
  90. , clientDimension
  91. , clientAxis
  92. , position
  93. , gutterClass
  94. , paddingA
  95. , paddingB
  96. , pairs = []
  97. // 1. Set defaults to something sane. `options` doesn't have to be passed at all,
  98. // so create an options object if none exists. Pixel values 10, 100 and 30 are
  99. // arbitrary but feel natural.
  100. options = typeof options !== 'undefined' ? options : {}
  101. if (typeof options.gutterSize === 'undefined') options.gutterSize = 10
  102. if (typeof options.minSize === 'undefined') options.minSize = 100
  103. if (typeof options.snapOffset === 'undefined') options.snapOffset = 30
  104. if (typeof options.direction === 'undefined') options.direction = 'horizontal'
  105. // 2. Initialize a bunch of strings based on the direction we're splitting.
  106. // A lot of the behavior in the rest of the library is paramatized down to
  107. // rely on CSS strings and classes.
  108. if (options.direction == 'horizontal') {
  109. dimension = 'width'
  110. clientDimension = 'clientWidth'
  111. clientAxis = 'clientX'
  112. position = 'left'
  113. gutterClass = 'gutter gutter-horizontal'
  114. paddingA = 'paddingLeft'
  115. paddingB = 'paddingRight'
  116. if (!options.cursor) options.cursor = 'ew-resize'
  117. } else if (options.direction == 'vertical') {
  118. dimension = 'height'
  119. clientDimension = 'clientHeight'
  120. clientAxis = 'clientY'
  121. position = 'top'
  122. gutterClass = 'gutter gutter-vertical'
  123. paddingA = 'paddingTop'
  124. paddingB = 'paddingBottom'
  125. if (!options.cursor) options.cursor = 'ns-resize'
  126. }
  127. if (options.blockDrag) gutterClass += ' blocked'
  128. // 3. Define the dragging helper functions, and a few helpers to go with them.
  129. // Each helper is bound to a pair object that contains it's metadata. This
  130. // also makes it easy to store references to listeners that that will be
  131. // added and removed.
  132. //
  133. // Even though there are no other functions contained in them, aliasing
  134. // this to self saves 50 bytes or so since it's used so frequently.
  135. //
  136. // The pair object saves metadata like dragging state, position and
  137. // event listener references.
  138. //
  139. // startDragging calls `calculateSizes` to store the inital size in the pair object.
  140. // It also adds event listeners for mouse/touch events,
  141. // and prevents selection while dragging so avoid the selecting text.
  142. var startDragging = function (e) {
  143. if (!options.blockDrag) {
  144. // Alias frequently used variables to save space. 200 bytes.
  145. var self = this
  146. , a = self.a
  147. , b = self.b
  148. // Call the onDragStart callback.
  149. if (!self.dragging && options.onDragStart) {
  150. options.onDragStart()
  151. }
  152. // Don't actually drag the element. We emulate that in the drag function.
  153. e.preventDefault()
  154. // Set the dragging property of the pair object.
  155. self.dragging = true
  156. // Create two event listeners bound to the same pair object and store
  157. // them in the pair object.
  158. self.move = drag.bind(self)
  159. self.stop = stopDragging.bind(self)
  160. // All the binding. `window` gets the stop events in case we drag out of the elements.
  161. global[addEventListener]('mouseup', self.stop)
  162. global[addEventListener]('touchend', self.stop)
  163. global[addEventListener]('touchcancel', self.stop)
  164. self.parent[addEventListener]('mousemove', self.move)
  165. self.parent[addEventListener]('touchmove', self.move)
  166. // Disable selection. Disable!
  167. a[addEventListener]('selectstart', noop)
  168. a[addEventListener]('dragstart', noop)
  169. b[addEventListener]('selectstart', noop)
  170. b[addEventListener]('dragstart', noop)
  171. a.style.userSelect = 'none'
  172. a.style.webkitUserSelect = 'none'
  173. a.style.MozUserSelect = 'none'
  174. a.style.pointerEvents = 'none'
  175. b.style.userSelect = 'none'
  176. b.style.webkitUserSelect = 'none'
  177. b.style.MozUserSelect = 'none'
  178. b.style.pointerEvents = 'none'
  179. // Set the cursor, both on the gutter and the parent element.
  180. // Doing only a, b and gutter causes flickering.
  181. self.gutter.style.cursor = options.cursor
  182. self.parent.style.cursor = options.cursor
  183. // Cache the initial sizes of the pair.
  184. calculateSizes.call(self)
  185. }
  186. }
  187. // stopDragging is very similar to startDragging in reverse.
  188. , stopDragging = function () {
  189. if (!options.blockDrag) {
  190. var self = this
  191. , a = self.a
  192. , b = self.b
  193. if (self.dragging && options.onDragEnd) {
  194. options.onDragEnd()
  195. }
  196. self.dragging = false
  197. // Remove the stored event listeners. This is why we store them.
  198. global[removeEventListener]('mouseup', self.stop)
  199. global[removeEventListener]('touchend', self.stop)
  200. global[removeEventListener]('touchcancel', self.stop)
  201. self.parent[removeEventListener]('mousemove', self.move)
  202. self.parent[removeEventListener]('touchmove', self.move)
  203. // Delete them once they are removed. I think this makes a difference
  204. // in memory usage with a lot of splits on one page. But I don't know for sure.
  205. delete self.stop
  206. delete self.move
  207. a[removeEventListener]('selectstart', noop)
  208. a[removeEventListener]('dragstart', noop)
  209. b[removeEventListener]('selectstart', noop)
  210. b[removeEventListener]('dragstart', noop)
  211. a.style.userSelect = ''
  212. a.style.webkitUserSelect = ''
  213. a.style.MozUserSelect = ''
  214. a.style.pointerEvents = ''
  215. b.style.userSelect = ''
  216. b.style.webkitUserSelect = ''
  217. b.style.MozUserSelect = ''
  218. b.style.pointerEvents = ''
  219. self.gutter.style.cursor = ''
  220. self.parent.style.cursor = ''
  221. }
  222. }
  223. // drag, where all the magic happens. The logic is really quite simple:
  224. //
  225. // 1. Ignore if the pair is not dragging.
  226. // 2. Get the offset of the event.
  227. // 3. Snap offset to min if within snappable range (within min + snapOffset).
  228. // 4. Actually adjust each element in the pair to offset.
  229. //
  230. // ---------------------------------------------------------------------
  231. // | | <- this.aMin || this.bMin -> | |
  232. // | | | <- this.snapOffset || this.snapOffset -> | | |
  233. // | | | || | | |
  234. // | | | || | | |
  235. // ---------------------------------------------------------------------
  236. // | <- this.start this.size -> |
  237. , drag = function (e) {
  238. var offset
  239. if (!this.dragging) return
  240. // Get the offset of the event from the first side of the
  241. // pair `this.start`. Supports touch events, but not multitouch, so only the first
  242. // finger `touches[0]` is counted.
  243. if ('touches' in e) {
  244. offset = e.touches[0][clientAxis] - this.start
  245. } else {
  246. offset = e[clientAxis] - this.start
  247. }
  248. // If within snapOffset of min or max, set offset to min or max.
  249. // snapOffset buffers aMin and bMin, so logic is opposite for both.
  250. // Include the appropriate gutter sizes to prevent overflows.
  251. if (offset <= this.aMin + options.snapOffset + this.aGutterSize) {
  252. offset = this.aMin + this.aGutterSize
  253. } else if (offset >= this.size - (this.bMin + options.snapOffset + this.bGutterSize)) {
  254. offset = this.size - (this.bMin + this.bGutterSize)
  255. }
  256. // Actually adjust the size.
  257. adjust.call(this, offset)
  258. // Call the drag callback continously. Don't do anything too intensive
  259. // in this callback.
  260. if (options.onDrag) {
  261. options.onDrag()
  262. }
  263. }
  264. // Cache some important sizes when drag starts, so we don't have to do that
  265. // continously:
  266. //
  267. // `size`: The total size of the pair. First element + second element + first gutter + second gutter.
  268. // `percentage`: The percentage between 0-100 that the pair occupies in the parent.
  269. // `start`: The leading side of the first element.
  270. //
  271. // ------------------------------------------------ - - - - - - - - - - -
  272. // | aGutterSize -> ||| | |
  273. // | ||| | |
  274. // | ||| | |
  275. // | ||| <- bGutterSize | |
  276. // ------------------------------------------------ - - - - - - - - - - -
  277. // | <- start size -> | parentSize -> |
  278. , calculateSizes = function () {
  279. // Figure out the parent size minus padding.
  280. var computedStyle = global.getComputedStyle(this.parent)
  281. , parentSize = this.parent[clientDimension] - parseFloat(computedStyle[paddingA]) - parseFloat(computedStyle[paddingB])
  282. this.size = this.a[getBoundingClientRect]()[dimension] + this.b[getBoundingClientRect]()[dimension] + this.aGutterSize + this.bGutterSize
  283. this.percentage = Math.min(this.size / parentSize * 100, 100)
  284. this.start = this.a[getBoundingClientRect]()[position]
  285. }
  286. // Actually adjust the size of elements `a` and `b` to `offset` while dragging.
  287. // calc is used to allow calc(percentage + gutterpx) on the whole split instance,
  288. // which allows the viewport to be resized without additional logic.
  289. // Element a's size is the same as offset. b's size is total size - a size.
  290. // Both sizes are calculated from the initial parent percentage, then the gutter size is subtracted.
  291. , adjust = function (offset) {
  292. this.a.style[dimension] = calc + '(' + (offset / this.size * this.percentage) + '% - ' + this.aGutterSize + 'px)'
  293. this.b.style[dimension] = calc + '(' + (this.percentage - (offset / this.size * this.percentage)) + '% - ' + this.bGutterSize + 'px)'
  294. }
  295. // 4. Define a few more functions that "balance" the entire split instance.
  296. // Split.js tries it's best to cope with min sizes that don't add up.
  297. // At some point this should go away since it breaks out of the calc(% - px) model.
  298. // Maybe it's a user error if you pass uncomputable minSizes.
  299. , fitMin = function () {
  300. var self = this
  301. , a = self.a
  302. , b = self.b
  303. if (a[getBoundingClientRect]()[dimension] < self.aMin) {
  304. a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
  305. b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
  306. } else if (b[getBoundingClientRect]()[dimension] < self.bMin) {
  307. a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
  308. b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
  309. }
  310. }
  311. , fitMinReverse = function () {
  312. var self = this
  313. , a = self.a
  314. , b = self.b
  315. if (b[getBoundingClientRect]()[dimension] < self.bMin) {
  316. a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
  317. b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
  318. } else if (a[getBoundingClientRect]()[dimension] < self.aMin) {
  319. a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
  320. b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
  321. }
  322. }
  323. , balancePairs = function (pairs) {
  324. for (var i = 0; i < pairs.length; i++) {
  325. calculateSizes.call(pairs[i])
  326. fitMin.call(pairs[i])
  327. }
  328. for (i = pairs.length - 1; i >= 0; i--) {
  329. calculateSizes.call(pairs[i])
  330. fitMinReverse.call(pairs[i])
  331. }
  332. for (i = pairs.length - 1; i >= 0; i--) {
  333. adjust.call(pairs[i],pairs[i].a[getBoundingClientRect]()[dimension])
  334. }
  335. }
  336. , setElementSize = function (el, size, gutterSize) {
  337. // Split.js allows setting sizes via numbers (ideally), or if you must,
  338. // by string, like '300px'. This is less than ideal, because it breaks
  339. // the fluid layout that `calc(% - px)` provides. You're on your own if you do that,
  340. // make sure you calculate the gutter size by hand.
  341. if (typeof size !== 'string' && !(size instanceof String)) {
  342. if (!isIE8) {
  343. size = calc + '(' + size + '% - ' + gutterSize + 'px)'
  344. } else {
  345. size = options.sizes[i] + '%'
  346. }
  347. }
  348. el.style[dimension] = size
  349. }
  350. // No-op function to prevent default. Used to prevent selection.
  351. , noop = function () { return false }
  352. // All DOM elements in the split should have a common parent. We can grab
  353. // the first elements parent and hope users read the docs because the
  354. // behavior will be whacky otherwise.
  355. , parent = elementOrSelector(ids[0]).parentNode
  356. // Set default options.sizes to equal percentages of the parent element.
  357. if (!options.sizes) {
  358. var percent = 100 / ids.length
  359. options.sizes = []
  360. for (i = 0; i < ids.length; i++) {
  361. options.sizes.push(percent)
  362. }
  363. }
  364. // Standardize minSize to an array if it isn't already. This allows minSize
  365. // to be passed as a number.
  366. if (!Array.isArray(options.minSize)) {
  367. var minSizes = []
  368. for (i = 0; i < ids.length; i++) {
  369. minSizes.push(options.minSize)
  370. }
  371. options.minSize = minSizes
  372. }
  373. // 5. Loop through the elements while pairing them off. Every pair gets a
  374. // `pair` object, a gutter, and isFirst/isLast properties.
  375. //
  376. // Basic logic:
  377. //
  378. // - Starting with the second element `i > 0`, create `pair` objects with
  379. // `a = ids[i - 1]` and `b = ids[i]`
  380. // - Set gutter sizes based on the _pair_ being first/last. The first and last
  381. // pair have gutterSize / 2, since they only have one half gutter, and not two.
  382. // - Create gutter elements and add event listeners.
  383. // - Set the size of the elements, minus the gutter sizes.
  384. //
  385. // -----------------------------------------------------------------------
  386. // | i=0 | i=1 | i=2 | i=3 |
  387. // | | isFirst | | isLast |
  388. // | pair 0 pair 1 pair 2 |
  389. // | | | | |
  390. // -----------------------------------------------------------------------
  391. for (i = 0; i < ids.length; i++) {
  392. var el = elementOrSelector(ids[i])
  393. , isFirstPair = (i == 1)
  394. , isLastPair = (i == ids.length - 1)
  395. , size = options.sizes[i]
  396. , gutterSize = options.gutterSize
  397. , pair
  398. if (i > 0) {
  399. // Create the pair object with it's metadata.
  400. pair = {
  401. a: elementOrSelector(ids[i - 1]),
  402. b: el,
  403. aMin: options.minSize[i - 1],
  404. bMin: options.minSize[i],
  405. dragging: false,
  406. parent: parent,
  407. isFirst: isFirstPair,
  408. isLast: isLastPair,
  409. direction: options.direction
  410. }
  411. // For first and last pairs, first and last gutter width is half.
  412. pair.aGutterSize = options.gutterSize
  413. pair.bGutterSize = options.gutterSize
  414. if (isFirstPair) {
  415. pair.aGutterSize = options.gutterSize / 2
  416. }
  417. if (isLastPair) {
  418. pair.bGutterSize = options.gutterSize / 2
  419. }
  420. }
  421. // Determine the size of the current element. IE8 is supported by
  422. // staticly assigning sizes without draggable gutters. Assigns a string
  423. // to `size`.
  424. //
  425. // IE9 and above
  426. if (!isIE8) {
  427. // Create gutter elements for each pair.
  428. if (i > 0) {
  429. var gutter = document.createElement('div')
  430. gutter.className = gutterClass
  431. gutter.style[dimension] = options.gutterSize + 'px'
  432. gutter[addEventListener]('mousedown', startDragging.bind(pair))
  433. gutter[addEventListener]('touchstart', startDragging.bind(pair))
  434. parent.insertBefore(gutter, el)
  435. pair.gutter = gutter
  436. }
  437. // Half-size gutters for first and last elements.
  438. if (i === 0 || i == ids.length - 1) {
  439. gutterSize = options.gutterSize / 2
  440. }
  441. }
  442. // Set the element size to our determined size.
  443. setElementSize(el, size, gutterSize)
  444. // After the first iteration, and we have a pair object, append it to the
  445. // list of pairs.
  446. if (i > 0) {
  447. pairs.push(pair)
  448. }
  449. }
  450. // Balance the pairs to try to accomodate min sizes.
  451. //balancePairs(pairs)
  452. return {
  453. setSizes: function (sizes) {
  454. for (var i = 0; i < sizes.length; i++) {
  455. if (i > 0) {
  456. var pair = pairs[i - 1]
  457. setElementSize(pair.a, sizes[i - 1], pair.aGutterSize)
  458. setElementSize(pair.b, sizes[i], pair.bGutterSize)
  459. }
  460. }
  461. },
  462. collapse: function (i) {
  463. var pair
  464. if (i === pairs.length) {
  465. pair = pairs[i - 1]
  466. calculateSizes.call(pair)
  467. adjust.call(pair, pair.size - pair.bGutterSize)
  468. } else {
  469. pair = pairs[i]
  470. calculateSizes.call(pair)
  471. adjust.call(pair, pair.aGutterSize)
  472. }
  473. },
  474. destroy: function () {
  475. for (var i = 0; i < pairs.length; i++) {
  476. pairs[i].parent.removeChild(pairs[i].gutter)
  477. pairs[i].a.style[dimension] = ''
  478. pairs[i].b.style[dimension] = ''
  479. }
  480. }
  481. }
  482. }
  483. // Play nicely with module systems, and the browser too if you include it raw.
  484. if (typeof exports !== 'undefined') {
  485. if (typeof module !== 'undefined' && module.exports) {
  486. exports = module.exports = Split
  487. }
  488. exports.Split = Split
  489. } else {
  490. global.Split = Split
  491. }
  492. // Call our wrapper function with the current global. In this case, `window`.
  493. }).call(window);