page.coffee 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. currentState = context.state
  37. page.dispatch(context)
  38. context.pushState()
  39. updateCanonicalLink()
  40. track()
  41. context
  42. page.replace = (path, state, skipDispatch, init) ->
  43. context = new Context(path, state or currentState)
  44. context.init = init
  45. currentState = context.state
  46. page.dispatch(context) unless skipDispatch
  47. context.replaceState()
  48. updateCanonicalLink()
  49. track() unless init or skipDispatch
  50. context
  51. page.dispatch = (context) ->
  52. i = 0
  53. next = ->
  54. fn(context, next) if fn = callbacks[i++]
  55. return
  56. next()
  57. return
  58. page.canGoBack = ->
  59. not Context.isIntialState(currentState)
  60. page.canGoForward = ->
  61. not Context.isLastState(currentState)
  62. currentPath = ->
  63. location.pathname + location.search + location.hash
  64. class Context
  65. @initialPath: currentPath()
  66. @sessionId: Date.now()
  67. @stateId: 0
  68. @isIntialState: (state) ->
  69. state.id == 0
  70. @isLastState: (state) ->
  71. state.id == @stateId - 1
  72. @isInitialPopState: (state) ->
  73. state.path is @initialPath and @stateId is 1
  74. @isSameSession: (state) ->
  75. state.sessionId is @sessionId
  76. constructor: (@path = '/', @state = {}) ->
  77. @pathname = @path.replace /(?:\?([^#]*))?(?:#(.*))?$/, (_, query, hash) =>
  78. @query = query
  79. @hash = hash
  80. ''
  81. @state.id ?= @constructor.stateId++
  82. @state.sessionId ?= @constructor.sessionId
  83. @state.path = @path
  84. pushState: ->
  85. history.pushState @state, '', @path
  86. return
  87. replaceState: ->
  88. try history.replaceState @state, '', @path # NS_ERROR_FAILURE in Firefox
  89. return
  90. class Route
  91. constructor: (@path, options = {}) ->
  92. @keys = []
  93. @regexp = pathtoRegexp @path, @keys
  94. middleware: (fn) ->
  95. (context, next) =>
  96. if @match context.pathname, params = []
  97. context.params = params
  98. fn(context, next)
  99. else
  100. next()
  101. return
  102. match: (path, params) ->
  103. return unless matchData = @regexp.exec(path)
  104. for value, i in matchData[1..]
  105. value = decodeURIComponent value if typeof value is 'string'
  106. if key = @keys[i]
  107. params[key.name] = value
  108. else
  109. params.push value
  110. true
  111. pathtoRegexp = (path, keys) ->
  112. return path if path instanceof RegExp
  113. path = "(#{path.join '|'})" if path instanceof Array
  114. path = path
  115. .replace /\/\(/g, '(?:/'
  116. .replace /(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, (_, slash = '', format = '', key, capture, optional) ->
  117. keys.push name: key, optional: !!optional
  118. str = if optional then '' else slash
  119. str += '(?:'
  120. str += slash if optional
  121. str += format
  122. str += capture or if format then '([^/.]+?)' else '([^/]+?)'
  123. str += ')'
  124. str += optional if optional
  125. str
  126. .replace /([\/.])/g, '\\$1'
  127. .replace /\*/g, '(.*)'
  128. new RegExp "^#{path}$"
  129. onpopstate = (event) ->
  130. return if not event.state or Context.isInitialPopState(event.state)
  131. if Context.isSameSession(event.state)
  132. page.replace(event.state.path, event.state)
  133. else
  134. location.reload()
  135. return
  136. onclick = (event) ->
  137. try
  138. return if event.which isnt 1 or event.metaKey or event.ctrlKey or event.shiftKey or event.defaultPrevented
  139. catch
  140. return
  141. link = event.target
  142. link = link.parentElement while link and link.tagName isnt 'A'
  143. if link and not link.target and isSameOrigin(link.href)
  144. event.preventDefault()
  145. page.show link.pathname + link.search + link.hash
  146. return
  147. isSameOrigin = (url) ->
  148. url.indexOf("#{location.protocol}//#{location.hostname}") is 0
  149. updateCanonicalLink = ->
  150. @canonicalLink ||= document.head.querySelector('link[rel="canonical"]')
  151. @canonicalLink.setAttribute('href', "http://#{location.host}#{location.pathname}")
  152. track = ->
  153. ga?('send', 'pageview', location.pathname + location.search + location.hash)
  154. _gauges?.push(['track'])
  155. return