util.coffee 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #
  2. # Traversing
  3. #
  4. @$ = (selector, el = document) ->
  5. try el.querySelector(selector) catch
  6. @$$ = (selector, el = document) ->
  7. try el.querySelectorAll(selector) catch
  8. $.id = (id) ->
  9. document.getElementById(id)
  10. $.hasChild = (parent, el) ->
  11. return unless parent
  12. while el
  13. return true if el is parent
  14. return if el is document.body
  15. el = el.parentElement
  16. $.closestLink = (el, parent = document.body) ->
  17. while el
  18. return el if el.tagName is 'A'
  19. return if el is parent
  20. el = el.parentElement
  21. #
  22. # Events
  23. #
  24. $.on = (el, event, callback, useCapture = false) ->
  25. if event.indexOf(' ') >= 0
  26. $.on el, name, callback for name in event.split(' ')
  27. else
  28. el.addEventListener(event, callback, useCapture)
  29. return
  30. $.off = (el, event, callback, useCapture = false) ->
  31. if event.indexOf(' ') >= 0
  32. $.off el, name, callback for name in event.split(' ')
  33. else
  34. el.removeEventListener(event, callback, useCapture)
  35. return
  36. $.trigger = (el, type, canBubble = true, cancelable = true) ->
  37. event = document.createEvent 'Event'
  38. event.initEvent(type, canBubble, cancelable)
  39. el.dispatchEvent(event)
  40. return
  41. $.click = (el) ->
  42. event = document.createEvent 'MouseEvent'
  43. event.initMouseEvent 'click', true, true, window, null, 0, 0, 0, 0, false, false, false, false, 0, null
  44. el.dispatchEvent(event)
  45. return
  46. $.stopEvent = (event) ->
  47. event.preventDefault()
  48. event.stopPropagation()
  49. event.stopImmediatePropagation()
  50. return
  51. #
  52. # Manipulation
  53. #
  54. buildFragment = (value) ->
  55. fragment = document.createDocumentFragment()
  56. if $.isCollection(value)
  57. fragment.appendChild(child) for child in $.makeArray(value)
  58. else
  59. fragment.innerHTML = value
  60. fragment
  61. $.append = (el, value) ->
  62. if typeof value is 'string'
  63. el.insertAdjacentHTML 'beforeend', value
  64. else
  65. value = buildFragment(value) if $.isCollection(value)
  66. el.appendChild(value)
  67. return
  68. $.prepend = (el, value) ->
  69. if not el.firstChild
  70. $.append(value)
  71. else if typeof value is 'string'
  72. el.insertAdjacentHTML 'afterbegin', value
  73. else
  74. value = buildFragment(value) if $.isCollection(value)
  75. el.insertBefore(value, el.firstChild)
  76. return
  77. $.before = (el, value) ->
  78. if typeof value is 'string' or $.isCollection(value)
  79. value = buildFragment(value)
  80. el.parentElement.insertBefore(value, el)
  81. return
  82. $.after = (el, value) ->
  83. if typeof value is 'string' or $.isCollection(value)
  84. value = buildFragment(value)
  85. if el.nextSibling
  86. el.parentElement.insertBefore(value, el.nextSibling)
  87. else
  88. el.parentElement.appendChild(value)
  89. return
  90. $.remove = (value) ->
  91. if $.isCollection(value)
  92. el.parentElement?.removeChild(el) for el in $.makeArray(value)
  93. else
  94. value.parentElement?.removeChild(value)
  95. return
  96. $.empty = (el) ->
  97. el.removeChild(el.firstChild) while el.firstChild
  98. return
  99. # Calls the function while the element is off the DOM to avoid triggering
  100. # unecessary reflows and repaints.
  101. $.batchUpdate = (el, fn) ->
  102. parent = el.parentNode
  103. sibling = el.nextSibling
  104. parent.removeChild(el)
  105. fn(el)
  106. if (sibling)
  107. parent.insertBefore(el, sibling)
  108. else
  109. parent.appendChild(el)
  110. return
  111. #
  112. # Offset
  113. #
  114. $.rect = (el) ->
  115. el.getBoundingClientRect()
  116. $.offset = (el, container = document.body) ->
  117. top = 0
  118. left = 0
  119. while el and el isnt container
  120. top += el.offsetTop
  121. left += el.offsetLeft
  122. el = el.offsetParent
  123. top: top
  124. left: left
  125. $.scrollParent = (el) ->
  126. while el = el.parentElement
  127. break if el.scrollTop > 0
  128. break if getComputedStyle(el)?.overflowY in ['auto', 'scroll']
  129. el
  130. $.scrollTo = (el, parent, position = 'center', options = {}) ->
  131. return unless el
  132. parent ?= $.scrollParent(el)
  133. return unless parent
  134. parentHeight = parent.clientHeight
  135. return unless parent.scrollHeight > parentHeight
  136. top = $.offset(el, parent).top
  137. offsetTop = parent.firstElementChild.offsetTop
  138. switch position
  139. when 'top'
  140. parent.scrollTop = top - offsetTop - (if options.margin? then options.margin else 0)
  141. when 'center'
  142. parent.scrollTop = top - Math.round(parentHeight / 2 - el.offsetHeight / 2)
  143. when 'continuous'
  144. scrollTop = parent.scrollTop
  145. height = el.offsetHeight
  146. # If the target element is above the visible portion of its scrollable
  147. # ancestor, move it near the top with a gap = options.topGap * target's height.
  148. if top - offsetTop <= scrollTop + height * (options.topGap or 1)
  149. parent.scrollTop = top - offsetTop - height * (options.topGap or 1)
  150. # If the target element is below the visible portion of its scrollable
  151. # ancestor, move it near the bottom with a gap = options.bottomGap * target's height.
  152. else if top >= scrollTop + parentHeight - height * ((options.bottomGap or 1) + 1)
  153. parent.scrollTop = top - parentHeight + height * ((options.bottomGap or 1) + 1)
  154. return
  155. $.scrollToWithImageLock = (el, parent, args...) ->
  156. parent ?= $.scrollParent(el)
  157. return unless parent
  158. $.scrollTo el, parent, args...
  159. # Lock the scroll position on the target element for up to 3 seconds while
  160. # nearby images are loaded and rendered.
  161. for image in parent.getElementsByTagName('img') when not image.complete
  162. do ->
  163. onLoad = (event) ->
  164. clearTimeout(timeout)
  165. unbind(event.target)
  166. $.scrollTo el, parent, args...
  167. unbind = (target) ->
  168. $.off target, 'load', onLoad
  169. $.on image, 'load', onLoad
  170. timeout = setTimeout unbind.bind(null, image), 3000
  171. return
  172. # Calls the function while locking the element's position relative to the window.
  173. $.lockScroll = (el, fn) ->
  174. if parent = $.scrollParent(el)
  175. top = $.rect(el).top
  176. top -= $.rect(parent).top unless parent in [document.body, document.documentElement]
  177. fn()
  178. parent.scrollTop = $.offset(el, parent).top - top
  179. else
  180. fn()
  181. return
  182. smoothScroll = smoothStart = smoothEnd = smoothDistance = smoothDuration = null
  183. $.smoothScroll = (el, end) ->
  184. unless window.requestAnimationFrame
  185. el.scrollTop = end
  186. return
  187. smoothEnd = end
  188. if smoothScroll
  189. newDistance = smoothEnd - smoothStart
  190. smoothDuration += Math.min 300, Math.abs(smoothDistance - newDistance)
  191. smoothDistance = newDistance
  192. return
  193. smoothStart = el.scrollTop
  194. smoothDistance = smoothEnd - smoothStart
  195. smoothDuration = Math.min 300, Math.abs(smoothDistance)
  196. startTime = Date.now()
  197. smoothScroll = ->
  198. p = Math.min 1, (Date.now() - startTime) / smoothDuration
  199. y = Math.max 0, Math.floor(smoothStart + smoothDistance * (if p < 0.5 then 2 * p * p else p * (4 - p * 2) - 1))
  200. el.scrollTop = y
  201. if p is 1
  202. smoothScroll = null
  203. else
  204. requestAnimationFrame(smoothScroll)
  205. requestAnimationFrame(smoothScroll)
  206. #
  207. # Utilities
  208. #
  209. $.extend = (target, objects...) ->
  210. for object in objects when object
  211. for key, value of object
  212. target[key] = value
  213. target
  214. $.makeArray = (object) ->
  215. if Array.isArray(object)
  216. object
  217. else
  218. Array::slice.apply(object)
  219. $.arrayDelete = (array, object) ->
  220. index = array.indexOf(object)
  221. if index >= 0
  222. array.splice(index, 1)
  223. true
  224. else
  225. false
  226. # Returns true if the object is an array or a collection of DOM elements.
  227. $.isCollection = (object) ->
  228. Array.isArray(object) or typeof object?.item is 'function'
  229. ESCAPE_HTML_MAP =
  230. '&': '&amp;'
  231. '<': '&lt;'
  232. '>': '&gt;'
  233. '"': '&quot;'
  234. "'": '&#x27;'
  235. '/': '&#x2F;'
  236. ESCAPE_HTML_REGEXP = /[&<>"'\/]/g
  237. $.escape = (string) ->
  238. string.replace ESCAPE_HTML_REGEXP, (match) -> ESCAPE_HTML_MAP[match]
  239. ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g
  240. $.escapeRegexp = (string) ->
  241. string.replace ESCAPE_REGEXP, "\\$1"
  242. $.urlDecode = (string) ->
  243. decodeURIComponent string.replace(/\+/g, '%20')
  244. $.classify = (string) ->
  245. string = string.split('_')
  246. for substr, i in string
  247. string[i] = substr[0].toUpperCase() + substr[1..]
  248. string.join('')
  249. $.framify = (fn, obj) ->
  250. if window.requestAnimationFrame
  251. (args...) -> requestAnimationFrame(fn.bind(obj, args...))
  252. else
  253. fn
  254. $.requestAnimationFrame = (fn) ->
  255. if window.requestAnimationFrame
  256. requestAnimationFrame(fn)
  257. else
  258. setTimeout(fn, 0)
  259. return
  260. #
  261. # Miscellaneous
  262. #
  263. $.noop = ->
  264. $.popup = (value) ->
  265. win = window.open()
  266. if win
  267. win.opener = null if win.opener
  268. win.location = value.href or value
  269. else
  270. window.open value.href or value, '_blank'
  271. return
  272. isMac = null
  273. $.isMac = ->
  274. isMac ?= navigator.userAgent?.indexOf('Mac') >= 0
  275. isIE = null
  276. $.isIE = ->
  277. isIE ?= navigator.userAgent?.indexOf('MSIE') >= 0 || navigator.userAgent?.indexOf('rv:11.0') >= 0
  278. isAndroid = null
  279. $.isAndroid = ->
  280. isAndroid ?= navigator.userAgent?.indexOf('Android') >= 0
  281. isIOS = null
  282. $.isIOS = ->
  283. isIOS ?= navigator.userAgent?.indexOf('iPhone') >= 0 || navigator.userAgent?.indexOf('iPad') >= 0
  284. HIGHLIGHT_DEFAULTS =
  285. className: 'highlight'
  286. delay: 1000
  287. $.highlight = (el, options = {}) ->
  288. options = $.extend {}, HIGHLIGHT_DEFAULTS, options
  289. el.classList.add(options.className)
  290. setTimeout (-> el.classList.remove(options.className)), options.delay
  291. return
  292. $.copyToClipboard = (string) ->
  293. textarea = document.createElement('textarea')
  294. textarea.style.position = 'fixed'
  295. textarea.style.opacity = 0
  296. textarea.value = string
  297. document.body.appendChild(textarea)
  298. try
  299. textarea.select()
  300. result = !!document.execCommand('copy')
  301. catch
  302. result = false
  303. finally
  304. document.body.removeChild(textarea)
  305. result