split.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. // 3. Define the dragging helper functions, and a few helpers to go with them.
  128. // Each helper is bound to a pair object that contains it's metadata. This
  129. // also makes it easy to store references to listeners that that will be
  130. // added and removed.
  131. //
  132. // Even though there are no other functions contained in them, aliasing
  133. // this to self saves 50 bytes or so since it's used so frequently.
  134. //
  135. // The pair object saves metadata like dragging state, position and
  136. // event listener references.
  137. //
  138. // startDragging calls `calculateSizes` to store the inital size in the pair object.
  139. // It also adds event listeners for mouse/touch events,
  140. // and prevents selection while dragging so avoid the selecting text.
  141. var startDragging = function (e) {
  142. // Alias frequently used variables to save space. 200 bytes.
  143. var self = this
  144. , a = self.a
  145. , b = self.b
  146. // Call the onDragStart callback.
  147. if (!self.dragging && options.onDragStart) {
  148. options.onDragStart()
  149. }
  150. // Don't actually drag the element. We emulate that in the drag function.
  151. e.preventDefault()
  152. // Set the dragging property of the pair object.
  153. self.dragging = true
  154. // Create two event listeners bound to the same pair object and store
  155. // them in the pair object.
  156. self.move = drag.bind(self)
  157. self.stop = stopDragging.bind(self)
  158. // All the binding. `window` gets the stop events in case we drag out of the elements.
  159. global[addEventListener]('mouseup', self.stop)
  160. global[addEventListener]('touchend', self.stop)
  161. global[addEventListener]('touchcancel', self.stop)
  162. self.parent[addEventListener]('mousemove', self.move)
  163. self.parent[addEventListener]('touchmove', self.move)
  164. // Disable selection. Disable!
  165. a[addEventListener]('selectstart', noop)
  166. a[addEventListener]('dragstart', noop)
  167. b[addEventListener]('selectstart', noop)
  168. b[addEventListener]('dragstart', noop)
  169. a.style.userSelect = 'none'
  170. a.style.webkitUserSelect = 'none'
  171. a.style.MozUserSelect = 'none'
  172. a.style.pointerEvents = 'none'
  173. b.style.userSelect = 'none'
  174. b.style.webkitUserSelect = 'none'
  175. b.style.MozUserSelect = 'none'
  176. b.style.pointerEvents = 'none'
  177. // Set the cursor, both on the gutter and the parent element.
  178. // Doing only a, b and gutter causes flickering.
  179. self.gutter.style.cursor = options.cursor
  180. self.parent.style.cursor = options.cursor
  181. // Cache the initial sizes of the pair.
  182. calculateSizes.call(self)
  183. }
  184. // stopDragging is very similar to startDragging in reverse.
  185. , stopDragging = function () {
  186. var self = this
  187. , a = self.a
  188. , b = self.b
  189. if (self.dragging && options.onDragEnd) {
  190. options.onDragEnd()
  191. }
  192. self.dragging = false
  193. // Remove the stored event listeners. This is why we store them.
  194. global[removeEventListener]('mouseup', self.stop)
  195. global[removeEventListener]('touchend', self.stop)
  196. global[removeEventListener]('touchcancel', self.stop)
  197. self.parent[removeEventListener]('mousemove', self.move)
  198. self.parent[removeEventListener]('touchmove', self.move)
  199. // Delete them once they are removed. I think this makes a difference
  200. // in memory usage with a lot of splits on one page. But I don't know for sure.
  201. delete self.stop
  202. delete self.move
  203. a[removeEventListener]('selectstart', noop)
  204. a[removeEventListener]('dragstart', noop)
  205. b[removeEventListener]('selectstart', noop)
  206. b[removeEventListener]('dragstart', noop)
  207. a.style.userSelect = ''
  208. a.style.webkitUserSelect = ''
  209. a.style.MozUserSelect = ''
  210. a.style.pointerEvents = ''
  211. b.style.userSelect = ''
  212. b.style.webkitUserSelect = ''
  213. b.style.MozUserSelect = ''
  214. b.style.pointerEvents = ''
  215. self.gutter.style.cursor = ''
  216. self.parent.style.cursor = ''
  217. }
  218. // drag, where all the magic happens. The logic is really quite simple:
  219. //
  220. // 1. Ignore if the pair is not dragging.
  221. // 2. Get the offset of the event.
  222. // 3. Snap offset to min if within snappable range (within min + snapOffset).
  223. // 4. Actually adjust each element in the pair to offset.
  224. //
  225. // ---------------------------------------------------------------------
  226. // | | <- this.aMin || this.bMin -> | |
  227. // | | | <- this.snapOffset || this.snapOffset -> | | |
  228. // | | | || | | |
  229. // | | | || | | |
  230. // ---------------------------------------------------------------------
  231. // | <- this.start this.size -> |
  232. , drag = function (e) {
  233. var offset
  234. if (!this.dragging) return
  235. // Get the offset of the event from the first side of the
  236. // pair `this.start`. Supports touch events, but not multitouch, so only the first
  237. // finger `touches[0]` is counted.
  238. if ('touches' in e) {
  239. offset = e.touches[0][clientAxis] - this.start
  240. } else {
  241. offset = e[clientAxis] - this.start
  242. }
  243. // If within snapOffset of min or max, set offset to min or max.
  244. // snapOffset buffers aMin and bMin, so logic is opposite for both.
  245. // Include the appropriate gutter sizes to prevent overflows.
  246. if (offset <= this.aMin + options.snapOffset + this.aGutterSize) {
  247. offset = this.aMin + this.aGutterSize
  248. } else if (offset >= this.size - (this.bMin + options.snapOffset + this.bGutterSize)) {
  249. offset = this.size - (this.bMin + this.bGutterSize)
  250. }
  251. // Actually adjust the size.
  252. adjust.call(this, offset)
  253. // Call the drag callback continously. Don't do anything too intensive
  254. // in this callback.
  255. if (options.onDrag) {
  256. options.onDrag()
  257. }
  258. }
  259. // Cache some important sizes when drag starts, so we don't have to do that
  260. // continously:
  261. //
  262. // `size`: The total size of the pair. First element + second element + first gutter + second gutter.
  263. // `percentage`: The percentage between 0-100 that the pair occupies in the parent.
  264. // `start`: The leading side of the first element.
  265. //
  266. // ------------------------------------------------ - - - - - - - - - - -
  267. // | aGutterSize -> ||| | |
  268. // | ||| | |
  269. // | ||| | |
  270. // | ||| <- bGutterSize | |
  271. // ------------------------------------------------ - - - - - - - - - - -
  272. // | <- start size -> | parentSize -> |
  273. , calculateSizes = function () {
  274. // Figure out the parent size minus padding.
  275. var computedStyle = global.getComputedStyle(this.parent)
  276. , parentSize = this.parent[clientDimension] - parseFloat(computedStyle[paddingA]) - parseFloat(computedStyle[paddingB])
  277. this.size = this.a[getBoundingClientRect]()[dimension] + this.b[getBoundingClientRect]()[dimension] + this.aGutterSize + this.bGutterSize
  278. this.percentage = Math.min(this.size / parentSize * 100, 100)
  279. this.start = this.a[getBoundingClientRect]()[position]
  280. }
  281. // Actually adjust the size of elements `a` and `b` to `offset` while dragging.
  282. // calc is used to allow calc(percentage + gutterpx) on the whole split instance,
  283. // which allows the viewport to be resized without additional logic.
  284. // Element a's size is the same as offset. b's size is total size - a size.
  285. // Both sizes are calculated from the initial parent percentage, then the gutter size is subtracted.
  286. , adjust = function (offset) {
  287. this.a.style[dimension] = calc + '(' + (offset / this.size * this.percentage) + '% - ' + this.aGutterSize + 'px)'
  288. this.b.style[dimension] = calc + '(' + (this.percentage - (offset / this.size * this.percentage)) + '% - ' + this.bGutterSize + 'px)'
  289. }
  290. // 4. Define a few more functions that "balance" the entire split instance.
  291. // Split.js tries it's best to cope with min sizes that don't add up.
  292. // At some point this should go away since it breaks out of the calc(% - px) model.
  293. // Maybe it's a user error if you pass uncomputable minSizes.
  294. , fitMin = function () {
  295. var self = this
  296. , a = self.a
  297. , b = self.b
  298. if (a[getBoundingClientRect]()[dimension] < self.aMin) {
  299. a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
  300. b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
  301. } else if (b[getBoundingClientRect]()[dimension] < self.bMin) {
  302. a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
  303. b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
  304. }
  305. }
  306. , fitMinReverse = function () {
  307. var self = this
  308. , a = self.a
  309. , b = self.b
  310. if (b[getBoundingClientRect]()[dimension] < self.bMin) {
  311. a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
  312. b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
  313. } else if (a[getBoundingClientRect]()[dimension] < self.aMin) {
  314. a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
  315. b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
  316. }
  317. }
  318. , balancePairs = function (pairs) {
  319. for (var i = 0; i < pairs.length; i++) {
  320. calculateSizes.call(pairs[i])
  321. fitMin.call(pairs[i])
  322. }
  323. for (i = pairs.length - 1; i >= 0; i--) {
  324. calculateSizes.call(pairs[i])
  325. fitMinReverse.call(pairs[i])
  326. }
  327. }
  328. , setElementSize = function (el, size, gutterSize) {
  329. // Split.js allows setting sizes via numbers (ideally), or if you must,
  330. // by string, like '300px'. This is less than ideal, because it breaks
  331. // the fluid layout that `calc(% - px)` provides. You're on your own if you do that,
  332. // make sure you calculate the gutter size by hand.
  333. if (typeof size !== 'string' && !(size instanceof String)) {
  334. if (!isIE8) {
  335. size = calc + '(' + size + '% - ' + gutterSize + 'px)'
  336. } else {
  337. size = options.sizes[i] + '%'
  338. }
  339. }
  340. el.style[dimension] = size
  341. }
  342. // No-op function to prevent default. Used to prevent selection.
  343. , noop = function () { return false }
  344. // All DOM elements in the split should have a common parent. We can grab
  345. // the first elements parent and hope users read the docs because the
  346. // behavior will be whacky otherwise.
  347. , parent = elementOrSelector(ids[0]).parentNode
  348. // Set default options.sizes to equal percentages of the parent element.
  349. if (!options.sizes) {
  350. var percent = 100 / ids.length
  351. options.sizes = []
  352. for (i = 0; i < ids.length; i++) {
  353. options.sizes.push(percent)
  354. }
  355. }
  356. // Standardize minSize to an array if it isn't already. This allows minSize
  357. // to be passed as a number.
  358. if (!Array.isArray(options.minSize)) {
  359. var minSizes = []
  360. for (i = 0; i < ids.length; i++) {
  361. minSizes.push(options.minSize)
  362. }
  363. options.minSize = minSizes
  364. }
  365. // 5. Loop through the elements while pairing them off. Every pair gets a
  366. // `pair` object, a gutter, and isFirst/isLast properties.
  367. //
  368. // Basic logic:
  369. //
  370. // - Starting with the second element `i > 0`, create `pair` objects with
  371. // `a = ids[i - 1]` and `b = ids[i]`
  372. // - Set gutter sizes based on the _pair_ being first/last. The first and last
  373. // pair have gutterSize / 2, since they only have one half gutter, and not two.
  374. // - Create gutter elements and add event listeners.
  375. // - Set the size of the elements, minus the gutter sizes.
  376. //
  377. // -----------------------------------------------------------------------
  378. // | i=0 | i=1 | i=2 | i=3 |
  379. // | | isFirst | | isLast |
  380. // | pair 0 pair 1 pair 2 |
  381. // | | | | |
  382. // -----------------------------------------------------------------------
  383. for (i = 0; i < ids.length; i++) {
  384. var el = elementOrSelector(ids[i])
  385. , isFirstPair = (i == 1)
  386. , isLastPair = (i == ids.length - 1)
  387. , size = options.sizes[i]
  388. , gutterSize = options.gutterSize
  389. , pair
  390. if (i > 0) {
  391. // Create the pair object with it's metadata.
  392. pair = {
  393. a: elementOrSelector(ids[i - 1]),
  394. b: el,
  395. aMin: options.minSize[i - 1],
  396. bMin: options.minSize[i],
  397. dragging: false,
  398. parent: parent,
  399. isFirst: isFirstPair,
  400. isLast: isLastPair,
  401. direction: options.direction
  402. }
  403. // For first and last pairs, first and last gutter width is half.
  404. pair.aGutterSize = options.gutterSize
  405. pair.bGutterSize = options.gutterSize
  406. if (isFirstPair) {
  407. pair.aGutterSize = options.gutterSize / 2
  408. }
  409. if (isLastPair) {
  410. pair.bGutterSize = options.gutterSize / 2
  411. }
  412. }
  413. // Determine the size of the current element. IE8 is supported by
  414. // staticly assigning sizes without draggable gutters. Assigns a string
  415. // to `size`.
  416. //
  417. // IE9 and above
  418. if (!isIE8) {
  419. // Create gutter elements for each pair.
  420. if (i > 0) {
  421. var gutter = document.createElement('div')
  422. gutter.className = gutterClass
  423. gutter.style[dimension] = options.gutterSize + 'px'
  424. gutter[addEventListener]('mousedown', startDragging.bind(pair))
  425. gutter[addEventListener]('touchstart', startDragging.bind(pair))
  426. parent.insertBefore(gutter, el)
  427. pair.gutter = gutter
  428. }
  429. // Half-size gutters for first and last elements.
  430. if (i === 0 || i == ids.length - 1) {
  431. gutterSize = options.gutterSize / 2
  432. }
  433. }
  434. // Set the element size to our determined size.
  435. setElementSize(el, size, gutterSize)
  436. // After the first iteration, and we have a pair object, append it to the
  437. // list of pairs.
  438. if (i > 0) {
  439. pairs.push(pair)
  440. }
  441. }
  442. // Balance the pairs to try to accomodate min sizes.
  443. //balancePairs(pairs)
  444. return {
  445. setSizes: function (sizes) {
  446. for (var i = 0; i < sizes.length; i++) {
  447. if (i > 0) {
  448. var pair = pairs[i - 1]
  449. setElementSize(pair.a, sizes[i - 1], pair.aGutterSize)
  450. setElementSize(pair.b, sizes[i], pair.bGutterSize)
  451. }
  452. }
  453. },
  454. collapse: function (i) {
  455. var pair
  456. if (i === pairs.length) {
  457. pair = pairs[i - 1]
  458. calculateSizes.call(pair)
  459. adjust.call(pair, pair.size - pair.bGutterSize)
  460. } else {
  461. pair = pairs[i]
  462. calculateSizes.call(pair)
  463. adjust.call(pair, pair.aGutterSize)
  464. }
  465. },
  466. destroy: function () {
  467. for (var i = 0; i < pairs.length; i++) {
  468. pairs[i].parent.removeChild(pairs[i].gutter)
  469. pairs[i].a.style[dimension] = ''
  470. pairs[i].b.style[dimension] = ''
  471. }
  472. }
  473. }
  474. }
  475. // Play nicely with module systems, and the browser too if you include it raw.
  476. if (typeof exports !== 'undefined') {
  477. if (typeof module !== 'undefined' && module.exports) {
  478. exports = module.exports = Split
  479. }
  480. exports.Split = Split
  481. } else {
  482. global.Split = Split
  483. }
  484. // Call our wrapper function with the current global. In this case, `window`.
  485. }).call(window);