page.coffee 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. ###
  2. * Based on github.com/visionmedia/page.js
  3. * Licensed under the MIT license
  4. * Copyright 2012 TJ Holowaychuk <tj@vision-media.ca>
  5. ###
  6. running = false
  7. currentState = null
  8. callbacks = []
  9. @page = (value, fn) ->
  10. if typeof value is 'function'
  11. page '*', value
  12. else if typeof fn is 'function'
  13. route = new Route(value)
  14. callbacks.push route.middleware(fn)
  15. else if typeof value is 'string'
  16. page.show(value, fn)
  17. else
  18. page.start(value)
  19. return
  20. page.start = (options = {}) ->
  21. unless running
  22. running = true
  23. addEventListener 'popstate', onpopstate
  24. addEventListener 'click', onclick
  25. page.replace currentPath(), null, null, true
  26. return
  27. page.stop = ->
  28. if running
  29. running = false
  30. removeEventListener 'click', onclick
  31. removeEventListener 'popstate', onpopstate
  32. return
  33. page.show = (path, state) ->
  34. return if path is currentState?.path
  35. context = new Context(path, state)
  36. previousState = currentState
  37. currentState = context.state
  38. if res = page.dispatch(context)
  39. currentState = previousState
  40. location.assign(res)
  41. else
  42. context.pushState()
  43. updateCanonicalLink()
  44. track()
  45. context
  46. page.replace = (path, state, skipDispatch, init) ->
  47. context = new Context(path, state or currentState)
  48. context.init = init
  49. currentState = context.state
  50. page.dispatch(context) unless skipDispatch
  51. context.replaceState()
  52. updateCanonicalLink()
  53. track() unless skipDispatch
  54. context
  55. page.dispatch = (context) ->
  56. i = 0
  57. next = ->
  58. res = fn(context, next) if fn = callbacks[i++]
  59. return res
  60. return next()
  61. page.canGoBack = ->
  62. not Context.isIntialState(currentState)
  63. page.canGoForward = ->
  64. not Context.isLastState(currentState)
  65. currentPath = ->
  66. location.pathname + location.search + location.hash
  67. class Context
  68. @initialPath: currentPath()
  69. @sessionId: Date.now()
  70. @stateId: 0
  71. @isIntialState: (state) ->
  72. state.id == 0
  73. @isLastState: (state) ->
  74. state.id == @stateId - 1
  75. @isInitialPopState: (state) ->
  76. state.path is @initialPath and @stateId is 1
  77. @isSameSession: (state) ->
  78. state.sessionId is @sessionId
  79. constructor: (@path = '/', @state = {}) ->
  80. @pathname = @path.replace /(?:\?([^#]*))?(?:#(.*))?$/, (_, query, hash) =>
  81. @query = query
  82. @hash = hash
  83. ''
  84. @state.id ?= @constructor.stateId++
  85. @state.sessionId ?= @constructor.sessionId
  86. @state.path = @path
  87. pushState: ->
  88. history.pushState @state, '', @path
  89. return
  90. replaceState: ->
  91. try history.replaceState @state, '', @path # NS_ERROR_FAILURE in Firefox
  92. return
  93. class Route
  94. constructor: (@path, options = {}) ->
  95. @keys = []
  96. @regexp = pathtoRegexp @path, @keys
  97. middleware: (fn) ->
  98. (context, next) =>
  99. if @match context.pathname, params = []
  100. context.params = params
  101. return fn(context, next)
  102. else
  103. return next()
  104. match: (path, params) ->
  105. return unless matchData = @regexp.exec(path)
  106. for value, i in matchData[1..]
  107. value = decodeURIComponent value if typeof value is 'string'
  108. if key = @keys[i]
  109. params[key.name] = value
  110. else
  111. params.push value
  112. true
  113. pathtoRegexp = (path, keys) ->
  114. return path if path instanceof RegExp
  115. path = "(#{path.join '|'})" if path instanceof Array
  116. path = path
  117. .replace /\/\(/g, '(?:/'
  118. .replace /(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, (_, slash = '', format = '', key, capture, optional) ->
  119. keys.push name: key, optional: !!optional
  120. str = if optional then '' else slash
  121. str += '(?:'
  122. str += slash if optional
  123. str += format
  124. str += capture or if format then '([^/.]+?)' else '([^/]+?)'
  125. str += ')'
  126. str += optional if optional
  127. str
  128. .replace /([\/.])/g, '\\$1'
  129. .replace /\*/g, '(.*)'
  130. new RegExp "^#{path}$"
  131. onpopstate = (event) ->
  132. return if not event.state or Context.isInitialPopState(event.state)
  133. if Context.isSameSession(event.state)
  134. page.replace(event.state.path, event.state)
  135. else
  136. location.reload()
  137. return
  138. onclick = (event) ->
  139. try
  140. return if event.which isnt 1 or event.metaKey or event.ctrlKey or event.shiftKey or event.defaultPrevented
  141. catch
  142. return
  143. link = $.eventTarget(event)
  144. link = link.parentNode while link and link.tagName isnt 'A'
  145. if link and not link.target and isSameOrigin(link.href)
  146. event.preventDefault()
  147. path = link.pathname + link.search + link.hash
  148. path = path.replace /^\/\/+/, '/' # IE11 bug
  149. page.show(path)
  150. return
  151. isSameOrigin = (url) ->
  152. url.indexOf("#{location.protocol}//#{location.hostname}") is 0
  153. updateCanonicalLink = ->
  154. @canonicalLink ||= document.head.querySelector('link[rel="canonical"]')
  155. @canonicalLink.setAttribute('href', "http://#{location.host}#{location.pathname}")
  156. trackers = []
  157. page.track = (fn) ->
  158. trackers.push(fn)
  159. return
  160. track = ->
  161. tracker.call() for tracker in trackers
  162. return