reader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import { HORIZONTAL_SLIDES_SELECTOR, SLIDES_SELECTOR } from '../utils/constants.js'
  2. import { queryAll, createStyleSheet } from '../utils/util.js'
  3. /**
  4. * The reader mode lets you read a reveal.js presentation
  5. * as a linear scrollable page.
  6. */
  7. export default class Reader {
  8. constructor( Reveal ) {
  9. this.Reveal = Reveal;
  10. this.active = false;
  11. this.activatedCallbacks = [];
  12. this.onScroll = this.onScroll.bind( this );
  13. }
  14. /**
  15. * Activates the reader mode. This rearranges the presentation DOM
  16. * by—among other things—wrapping each slide in a page element.
  17. */
  18. activate() {
  19. if( this.active ) return;
  20. const state = this.Reveal.getState();
  21. this.active = true;
  22. this.slideHTMLBeforeActivation = this.Reveal.getSlidesElement().innerHTML;
  23. const horizontalSlides = queryAll( this.Reveal.getRevealElement(), HORIZONTAL_SLIDES_SELECTOR );
  24. this.viewportElement.classList.add( 'loading-scroll-mode', 'reveal-reader' );
  25. this.viewportElement.addEventListener( 'scroll', this.onScroll );
  26. let presentationBackground;
  27. const viewportStyles = window.getComputedStyle( this.viewportElement );
  28. if( viewportStyles && viewportStyles.background ) {
  29. presentationBackground = viewportStyles.background;
  30. }
  31. const pageElements = [];
  32. const pageContainer = horizontalSlides[0].parentNode;
  33. function createPage( slide, h, v ) {
  34. // Wrap the slide in a page element and hide its overflow
  35. // so that no page ever flows onto another
  36. const page = document.createElement( 'div' );
  37. page.className = 'reader-page';
  38. pageElements.push( page );
  39. // Copy the presentation-wide background to each page
  40. if( presentationBackground ) {
  41. page.style.background = presentationBackground;
  42. }
  43. const stickyContainer = document.createElement( 'div' );
  44. stickyContainer.className = 'reader-page-sticky';
  45. page.appendChild( stickyContainer );
  46. const contentContainer = document.createElement( 'div' );
  47. contentContainer.className = 'reader-page-content';
  48. stickyContainer.appendChild( contentContainer );
  49. contentContainer.appendChild( slide );
  50. slide.classList.remove( 'past', 'future' );
  51. if( typeof h === 'number' ) slide.setAttribute( 'data-index-h', h );
  52. if( typeof v === 'number' ) slide.setAttribute( 'data-index-v', v );
  53. if( slide.slideBackgroundElement ) {
  54. slide.slideBackgroundElement.remove( 'past', 'future' );
  55. contentContainer.insertBefore( slide.slideBackgroundElement, slide );
  56. }
  57. }
  58. // Slide and slide background layout
  59. horizontalSlides.forEach( ( horizontalSlide, h ) => {
  60. if( this.Reveal.isVerticalStack( horizontalSlide ) ) {
  61. horizontalSlide.querySelectorAll( 'section' ).forEach( ( verticalSlide, v ) => {
  62. createPage( verticalSlide, h, v );
  63. });
  64. }
  65. else {
  66. createPage( horizontalSlide, h, 0 );
  67. }
  68. }, this );
  69. this.createProgressBar();
  70. // Remove leftover stacks
  71. queryAll( this.Reveal.getRevealElement(), '.stack' ).forEach( stack => stack.remove() );
  72. pageElements.forEach( page => pageContainer.appendChild( page ) );
  73. // Re-run JS-based content layout after the slide is added to page DOM
  74. this.Reveal.slideContent.layout( this.Reveal.getSlidesElement() );
  75. this.Reveal.layout();
  76. this.Reveal.setState( state );
  77. this.viewportElement.classList.remove( 'loading-scroll-mode' );
  78. this.activatedCallbacks.forEach( callback => callback() );
  79. this.activatedCallbacks = [];
  80. }
  81. createProgressBar() {
  82. this.progressBar = document.createElement( 'div' );
  83. this.progressBar.className = 'reader-progress';
  84. this.progressBarInner = document.createElement( 'div' );
  85. this.progressBarInner.className = 'reader-progress-inner';
  86. this.progressBar.appendChild( this.progressBarInner );
  87. this.progressBarPlayhead = document.createElement( 'div' );
  88. this.progressBarPlayhead.className = 'reader-progress-playhead';
  89. this.progressBarInner.appendChild( this.progressBarPlayhead );
  90. this.viewportElement.insertBefore( this.progressBar, this.viewportElement.firstChild );
  91. const handleMouseDown = ( event ) => {
  92. event.preventDefault();
  93. document.addEventListener( 'mousemove', handleDocumentMouseMove );
  94. document.addEventListener( 'mouseup', handleDocumentMouseUp );
  95. handleDocumentMouseMove( event );
  96. };
  97. const handleDocumentMouseMove = ( event ) => {
  98. let progress = Math.max( Math.min( ( event.clientY - this.progressBarInner.getBoundingClientRect().top ) / this.progressBarHeight, 1 ), 0 );
  99. progress = Math.max( Math.min( progress, 1 ), 0 );
  100. this.viewportElement.scrollTop = progress * ( this.viewportElement.scrollHeight - this.viewportElement.offsetHeight );
  101. };
  102. const handleDocumentMouseUp = ( event ) => {
  103. document.removeEventListener( 'mousemove', handleDocumentMouseMove );
  104. document.removeEventListener( 'mouseup', handleDocumentMouseUp );
  105. };
  106. this.progressBarInner.addEventListener( 'mousedown', handleMouseDown );
  107. }
  108. /**
  109. * Deactivates the reader mode and restores the standard slide-based
  110. * presentation.
  111. */
  112. deactivate() {
  113. if( !this.active ) return;
  114. const state = this.Reveal.getState();
  115. this.active = false;
  116. this.viewportElement.removeEventListener( 'scroll', this.onScroll );
  117. this.viewportElement.classList.remove( 'reveal-reader' );
  118. this.progressBar.remove();
  119. this.Reveal.getSlidesElement().innerHTML = this.slideHTMLBeforeActivation;
  120. this.Reveal.sync();
  121. this.Reveal.setState( state );
  122. }
  123. toggle( override ) {
  124. if( typeof override === 'boolean' ) {
  125. override ? this.activate() : this.deactivate();
  126. }
  127. else {
  128. this.isActive() ? this.deactivate() : this.activate();
  129. }
  130. }
  131. /**
  132. * Checks if the reader mode is currently active.
  133. */
  134. isActive() {
  135. return this.active;
  136. }
  137. /**
  138. * Retrieve a slide by its original h/v index (i.e. the indices the
  139. * slide had before being linearized).
  140. *
  141. * @param {number} h
  142. * @param {number} v
  143. * @returns {HTMLElement}
  144. */
  145. getSlideByIndices( h, v ) {
  146. const page = this.pages.find( page => page.indexh === h && page.indexv === v );
  147. return page ? page.slideElement : null;
  148. }
  149. /**
  150. * Updates our reader pages to match the latest configuration and
  151. * presentation size.
  152. */
  153. sync() {
  154. const config = this.Reveal.getConfig();
  155. const slideSize = this.Reveal.getComputedSlideSize( window.innerWidth, window.innerHeight );
  156. const scale = this.Reveal.getScale();
  157. const readerLayout = config.readerLayout;
  158. const viewportHeight = this.viewportElement.offsetHeight;
  159. const compactHeight = slideSize.height * scale;
  160. const pageHeight = readerLayout === 'full' ? viewportHeight : compactHeight;
  161. // The height that needs to be scrolled between scroll triggers
  162. const scrollTriggerHeight = viewportHeight;
  163. this.viewportElement.style.setProperty( '--page-height', pageHeight + 'px' );
  164. this.viewportElement.style.scrollSnapType = typeof config.readerScrollSnap === 'string' ?
  165. `y ${config.readerScrollSnap}` : '';
  166. const pageElements = Array.from( this.Reveal.getRevealElement().querySelectorAll( '.reader-page' ) );
  167. this.pages = pageElements.map( pageElement => {
  168. const page = {
  169. pageElement: pageElement,
  170. stickyElement: pageElement.querySelector( '.reader-page-sticky' ),
  171. slideElement: pageElement.querySelector( 'section' ),
  172. backgroundElement: pageElement.querySelector( '.slide-background' ),
  173. top: pageElement.offsetTop,
  174. scrollTriggers: [],
  175. };
  176. page.indexh = parseInt( page.slideElement.getAttribute( 'data-index-h' ), 10 );
  177. page.indexv = parseInt( page.slideElement.getAttribute( 'data-index-v' ), 10 );
  178. page.slideElement.style.width = slideSize.width + 'px';
  179. page.slideElement.style.height = config.center === true ? '' : slideSize.height + 'px';
  180. // Each fragment 'group' is an array containing one or more
  181. // fragments. Multiple fragments that appear at the same time
  182. // are part of the same group.
  183. page.fragments = this.Reveal.fragments.sort( pageElement.querySelectorAll( '.fragment:not(.disabled)' ) );
  184. page.fragmentGroups = this.Reveal.fragments.sort( pageElement.querySelectorAll( '.fragment' ), true );
  185. // Create scroll triggers that show/hide fragments
  186. if( page.fragmentGroups.length ) {
  187. const segmentSize = 1 / ( page.fragmentGroups.length + 1 );
  188. page.scrollTriggers.push(
  189. // Trigger for the initial state with no fragments visible
  190. { range: [ 0, segmentSize ], fragmentIndex: -1 },
  191. // Triggers for each fragment group
  192. ...page.fragmentGroups.map( ( fragments, i ) => ({
  193. range: [ segmentSize * ( i + 1 ), segmentSize * ( i + 2 ) ],
  194. fragmentIndex: i
  195. }))
  196. );
  197. }
  198. // Add scroll padding based on how many scroll triggers we have
  199. page.scrollPadding = scrollTriggerHeight * page.scrollTriggers.length;
  200. // In the compact layout, only slides with scroll triggers cover the
  201. // full viewport height. This helps avoid empty gaps before or after
  202. // a sticky slide.
  203. if( readerLayout === 'compact' && page.scrollTriggers.length > 0 ) {
  204. page.pageHeight = viewportHeight;
  205. page.pageElement.style.setProperty( '--page-height', viewportHeight + 'px' );
  206. }
  207. else {
  208. page.pageHeight = pageHeight;
  209. page.pageElement.style.removeProperty( '--page-height' );
  210. }
  211. page.pageElement.style.scrollSnapAlign = page.pageHeight < viewportHeight ? 'center' : 'start';
  212. // This variable is used to pad the height of our page in CSS
  213. page.pageElement.style.setProperty( '--page-scroll-padding', page.scrollPadding + 'px' );
  214. // The total height including scrollable space
  215. page.totalHeight = page.pageHeight + page.scrollPadding;
  216. page.bottom = page.top + page.totalHeight;
  217. // If this is a sticky page, stick it to the vertical center
  218. if( page.scrollTriggers.length > 0 ) {
  219. page.stickyElement.style.position = 'sticky';
  220. page.stickyElement.style.top = Math.max( ( viewportHeight - page.pageHeight ) / 2, 0 ) + 'px';
  221. // Make this page freeze at the vertical center of the viewport
  222. page.top -= ( viewportHeight - page.pageHeight ) / 2;
  223. }
  224. else {
  225. page.stickyElement.style.position = 'relative';
  226. }
  227. return page;
  228. } );
  229. this.createProgressBarSlides();
  230. }
  231. createProgressBarSlides() {
  232. this.progressBarInner.querySelectorAll( '.reader-progress-slide' ).forEach( slide => slide.remove() );
  233. const spacing = 4;
  234. const viewportHeight = this.viewportElement.offsetHeight;
  235. const scrollHeight = this.viewportElement.scrollHeight;
  236. this.progressBarHeight = this.progressBarInner.offsetHeight;
  237. this.playheadHeight = viewportHeight / scrollHeight * this.progressBarHeight;
  238. this.progressBarScrollableHeight = this.progressBarHeight - this.playheadHeight;
  239. this.progressBarPlayhead.style.height = this.playheadHeight - spacing + 'px';
  240. this.pages.forEach( page => {
  241. page.progressBarSlide = document.createElement( 'div' );
  242. page.progressBarSlide.className = 'reader-progress-slide';
  243. page.progressBarSlide.classList.toggle( 'has-triggers', page.scrollTriggers.length > 0 );
  244. page.progressBarSlide.style.top = page.top / scrollHeight * this.progressBarHeight + 'px';
  245. page.progressBarSlide.style.height = page.totalHeight / scrollHeight * this.progressBarHeight - spacing + 'px';
  246. this.progressBarInner.appendChild( page.progressBarSlide );
  247. page.scrollTriggers.forEach( trigger => {
  248. const triggerElement = document.createElement( 'div' );
  249. triggerElement.className = 'reader-progress-trigger';
  250. triggerElement.style.top = trigger.range[0] * page.totalHeight / scrollHeight * this.progressBarHeight + 'px';
  251. triggerElement.style.height = ( trigger.range[1] - trigger.range[0] ) * page.totalHeight / scrollHeight * this.progressBarHeight - spacing + 'px';
  252. page.progressBarSlide.appendChild( triggerElement );
  253. } );
  254. } );
  255. }
  256. layout() {
  257. if( this.isActive() ) {
  258. this.sync();
  259. this.onScroll();
  260. }
  261. }
  262. moveProgressBarTo( progress ) {
  263. this.progressBarPlayhead.style.transform = `translateY(${progress * this.progressBarScrollableHeight}px)`;
  264. this.pages.forEach( ( page ) => {
  265. page.progressBarSlide.classList.toggle( 'active', !!page.active );
  266. } );
  267. }
  268. scrollToSlide( slideElement ) {
  269. if( !this.active ) {
  270. this.activatedCallbacks.push( () => this.scrollToSlide( slideElement ) );
  271. }
  272. else {
  273. slideElement.parentNode.scrollIntoView();
  274. }
  275. }
  276. onScroll() {
  277. const viewportHeight = this.viewportElement.offsetHeight;
  278. const scrollTop = this.viewportElement.scrollTop;
  279. // Find the page closest to the center of the viewport, this
  280. // is the page we want to focus and activate
  281. const activePage = this.pages.reduce( ( closestPage, page ) => {
  282. // For tall pages with multiple scroll triggers we need to
  283. // check the distnace from both the top of the page and the
  284. // bottom
  285. const distance = Math.min(
  286. Math.abs( ( page.top + page.pageHeight / 2 ) - scrollTop - viewportHeight / 2 ),
  287. Math.abs( ( page.top + ( page.totalHeight - page.pageHeight / 2 ) ) - scrollTop - viewportHeight / 2 )
  288. );
  289. return distance < closestPage.distance ? { page, distance } : closestPage;
  290. }, { page: this.pages[0], distance: Infinity } ).page;
  291. this.pages.forEach( ( page, pageIndex ) => {
  292. const isWithinPreloadRange = scrollTop + viewportHeight >= page.top - viewportHeight && scrollTop < page.top + page.bottom + viewportHeight;
  293. const isPartiallyVisible = scrollTop + viewportHeight >= page.top && scrollTop < page.top + page.bottom;
  294. // Preload content when it appears within range
  295. if( isWithinPreloadRange ) {
  296. if( !page.preloaded ) {
  297. page.preloaded = true;
  298. this.Reveal.slideContent.load( page.slideElement );
  299. }
  300. }
  301. else if( page.preloaded ) {
  302. page.preloaded = false;
  303. this.Reveal.slideContent.unload( page.slideElement );
  304. }
  305. // Activate the current page — there can only be one active page at
  306. // a time.
  307. if( page === activePage ) {
  308. if( !page.active ) {
  309. page.active = true;
  310. page.pageElement.classList.add( 'present' );
  311. page.slideElement.classList.add( 'present' );
  312. this.Reveal.setCurrentReaderPage( page.pageElement, page.indexh, page.indexv );
  313. this.Reveal.slideContent.startEmbeddedContent( page.slideElement );
  314. if( page.backgroundElement ) {
  315. this.Reveal.slideContent.startEmbeddedContent( page.backgroundElement );
  316. }
  317. }
  318. }
  319. // Deactivate previously active pages
  320. else if( page.active ) {
  321. page.active = false;
  322. page.pageElement.classList.remove( 'present' );
  323. page.slideElement.classList.remove( 'present' );
  324. this.Reveal.slideContent.stopEmbeddedContent( page.slideElement );
  325. if( page.backgroundElement ) {
  326. this.Reveal.slideContent.stopEmbeddedContent( page.backgroundElement );
  327. }
  328. }
  329. // Handle scroll freezing and triggers for slides in view
  330. if( isPartiallyVisible && page.totalHeight > page.pageHeight ) {
  331. let scrollProgress = ( scrollTop - page.top ) / page.scrollPadding;
  332. scrollProgress = Math.max( Math.min( scrollProgress, 1 ), 0 );
  333. page.scrollTriggers.forEach( trigger => {
  334. if( scrollProgress >= trigger.range[0] && scrollProgress < trigger.range[1] ) {
  335. if( !trigger.active ) {
  336. trigger.active = true;
  337. this.Reveal.fragments.update( trigger.fragmentIndex, page.fragments, page.slideElement );
  338. }
  339. }
  340. else {
  341. trigger.active = false;
  342. }
  343. } );
  344. }
  345. } );
  346. this.moveProgressBarTo( scrollTop / ( this.viewportElement.scrollHeight - viewportHeight ) );
  347. }
  348. get viewportElement() {
  349. return this.Reveal.getViewportElement();
  350. }
  351. }