location.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /**
  2. * Reads and writes the URL based on reveal.js' current state.
  3. */
  4. export default class Location {
  5. // The minimum number of milliseconds that must pass between
  6. // calls to history.replaceState
  7. MAX_REPLACE_STATE_FREQUENCY = 1000
  8. constructor( Reveal ) {
  9. this.Reveal = Reveal;
  10. // Delays updates to the URL due to a Chrome thumbnailer bug
  11. this.writeURLTimeout = 0;
  12. this.replaceStateTimestamp = 0;
  13. this.onWindowHashChange = this.onWindowHashChange.bind( this );
  14. }
  15. bind() {
  16. window.addEventListener( 'hashchange', this.onWindowHashChange, false );
  17. }
  18. unbind() {
  19. window.removeEventListener( 'hashchange', this.onWindowHashChange, false );
  20. }
  21. /**
  22. * Returns the slide indices for the given hash link.
  23. *
  24. * @param {string} [hash] the hash string that we want to
  25. * find the indices for
  26. *
  27. * @returns slide indices or null
  28. */
  29. getIndicesFromHash( hash=window.location.hash ) {
  30. // Attempt to parse the hash as either an index or name
  31. let name = hash.replace( /^#\/?/, '' );
  32. let bits = name.split( '/' );
  33. // If the first bit is not fully numeric and there is a name we
  34. // can assume that this is a named link
  35. if( !/^[0-9]*$/.test( bits[0] ) && name.length ) {
  36. let element;
  37. let f;
  38. // Parse named links with fragments (#/named-link/2)
  39. if( /\/[-\d]+$/g.test( name ) ) {
  40. f = parseInt( name.split( '/' ).pop(), 10 );
  41. f = isNaN(f) ? undefined : f;
  42. name = name.split( '/' ).shift();
  43. }
  44. // Ensure the named link is a valid HTML ID attribute
  45. try {
  46. element = document.getElementById( decodeURIComponent( name ) );
  47. }
  48. catch ( error ) { }
  49. if( element ) {
  50. return { ...this.Reveal.getIndices( element ), f };
  51. }
  52. }
  53. else {
  54. const config = this.Reveal.getConfig();
  55. let hashIndexBase = config.hashOneBasedIndex ? 1 : 0;
  56. // Read the index components of the hash
  57. let h = ( parseInt( bits[0], 10 ) - hashIndexBase ) || 0,
  58. v = ( parseInt( bits[1], 10 ) - hashIndexBase ) || 0,
  59. f;
  60. if( config.fragmentInURL ) {
  61. f = parseInt( bits[2], 10 );
  62. if( isNaN( f ) ) {
  63. f = undefined;
  64. }
  65. }
  66. return { h, v, f };
  67. }
  68. // The hash couldn't be parsed or no matching named link was found
  69. return null
  70. }
  71. /**
  72. * Reads the current URL (hash) and navigates accordingly.
  73. */
  74. readURL() {
  75. const currentIndices = this.Reveal.getIndices();
  76. const newIndices = this.getIndicesFromHash();
  77. if( newIndices ) {
  78. if( ( newIndices.h !== currentIndices.h || newIndices.v !== currentIndices.v || newIndices.f !== undefined ) ) {
  79. this.Reveal.slide( newIndices.h, newIndices.v, newIndices.f );
  80. }
  81. }
  82. // If no new indices are available, we're trying to navigate to
  83. // a slide hash that does not exist
  84. else {
  85. this.Reveal.slide( currentIndices.h || 0, currentIndices.v || 0 );
  86. }
  87. }
  88. /**
  89. * Updates the page URL (hash) to reflect the current
  90. * state.
  91. *
  92. * @param {number} delay The time in ms to wait before
  93. * writing the hash
  94. */
  95. writeURL( delay ) {
  96. let config = this.Reveal.getConfig();
  97. let currentSlide = this.Reveal.getCurrentSlide();
  98. // Make sure there's never more than one timeout running
  99. clearTimeout( this.writeURLTimeout );
  100. // If a delay is specified, timeout this call
  101. if( typeof delay === 'number' ) {
  102. this.writeURLTimeout = setTimeout( this.writeURL, delay );
  103. }
  104. else if( currentSlide ) {
  105. let hash = this.getHash();
  106. // If we're configured to push to history OR the history
  107. // API is not avaialble.
  108. if( config.history ) {
  109. window.location.hash = hash;
  110. }
  111. // If we're configured to reflect the current slide in the
  112. // URL without pushing to history.
  113. else if( config.hash ) {
  114. // If the hash is empty, don't add it to the URL
  115. if( hash === '/' ) {
  116. this.debouncedReplaceState( window.location.pathname + window.location.search );
  117. }
  118. else {
  119. this.debouncedReplaceState( '#' + hash );
  120. }
  121. }
  122. // UPDATE: The below nuking of all hash changes breaks
  123. // anchors on pages where reveal.js is running. Removed
  124. // in 4.0. Why was it here in the first place? ¯\_(ツ)_/¯
  125. //
  126. // If history and hash are both disabled, a hash may still
  127. // be added to the URL by clicking on a href with a hash
  128. // target. Counter this by always removing the hash.
  129. // else {
  130. // window.history.replaceState( null, null, window.location.pathname + window.location.search );
  131. // }
  132. }
  133. }
  134. replaceState( url ) {
  135. window.history.replaceState( null, null, url );
  136. this.replaceStateTimestamp = Date.now();
  137. }
  138. debouncedReplaceState( url ) {
  139. clearTimeout( this.replaceStateTimeout );
  140. if( Date.now() - this.replaceStateTimestamp > this.MAX_REPLACE_STATE_FREQUENCY ) {
  141. this.replaceState( url );
  142. }
  143. else {
  144. this.replaceStateTimeout = setTimeout( () => this.replaceState( url ), this.MAX_REPLACE_STATE_FREQUENCY );
  145. }
  146. }
  147. /**
  148. * Return a hash URL that will resolve to the given slide location.
  149. *
  150. * @param {HTMLElement} [slide=currentSlide] The slide to link to
  151. */
  152. getHash( slide ) {
  153. let url = '/';
  154. // Attempt to create a named link based on the slide's ID
  155. let s = slide || this.Reveal.getCurrentSlide();
  156. let id = s ? s.getAttribute( 'id' ) : null;
  157. if( id ) {
  158. id = encodeURIComponent( id );
  159. }
  160. let index = this.Reveal.getIndices( slide );
  161. if( !this.Reveal.getConfig().fragmentInURL ) {
  162. index.f = undefined;
  163. }
  164. // If the current slide has an ID, use that as a named link,
  165. // but we don't support named links with a fragment index
  166. if( typeof id === 'string' && id.length ) {
  167. url = '/' + id;
  168. // If there is also a fragment, append that at the end
  169. // of the named link, like: #/named-link/2
  170. if( index.f >= 0 ) url += '/' + index.f;
  171. }
  172. // Otherwise use the /h/v index
  173. else {
  174. let hashIndexBase = this.Reveal.getConfig().hashOneBasedIndex ? 1 : 0;
  175. if( index.h > 0 || index.v > 0 || index.f >= 0 ) url += index.h + hashIndexBase;
  176. if( index.v > 0 || index.f >= 0 ) url += '/' + (index.v + hashIndexBase );
  177. if( index.f >= 0 ) url += '/' + index.f;
  178. }
  179. return url;
  180. }
  181. /**
  182. * Handler for the window level 'hashchange' event.
  183. *
  184. * @param {object} [event]
  185. */
  186. onWindowHashChange( event ) {
  187. this.readURL();
  188. }
  189. }