reader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. }
  92. /**
  93. * Deactivates the reader mode and restores the standard slide-based
  94. * presentation.
  95. */
  96. deactivate() {
  97. if( !this.active ) return;
  98. const state = this.Reveal.getState();
  99. this.active = false;
  100. this.viewportElement.removeEventListener( 'scroll', this.onScroll );
  101. this.viewportElement.classList.remove( 'reveal-reader' );
  102. this.progressBar.remove();
  103. this.Reveal.getSlidesElement().innerHTML = this.slideHTMLBeforeActivation;
  104. this.Reveal.sync();
  105. this.Reveal.setState( state );
  106. }
  107. toggle( override ) {
  108. if( typeof override === 'boolean' ) {
  109. override ? this.activate() : this.deactivate();
  110. }
  111. else {
  112. this.isActive() ? this.deactivate() : this.activate();
  113. }
  114. }
  115. /**
  116. * Checks if the reader mode is currently active.
  117. */
  118. isActive() {
  119. return this.active;
  120. }
  121. /**
  122. * Retrieve a slide by its original h/v index (i.e. the indices the
  123. * slide had before being linearized).
  124. *
  125. * @param {number} h
  126. * @param {number} v
  127. * @returns {HTMLElement}
  128. */
  129. getSlideByIndices( h, v ) {
  130. const page = this.pages.find( page => page.indexh === h && page.indexv === v );
  131. return page ? page.slideElement : null;
  132. }
  133. /**
  134. * Updates our reader pages to match the latest configuration and
  135. * presentation size.
  136. */
  137. sync() {
  138. const config = this.Reveal.getConfig();
  139. const slideSize = this.Reveal.getComputedSlideSize( window.innerWidth, window.innerHeight );
  140. const scale = this.Reveal.getScale();
  141. const readerLayout = config.readerLayout;
  142. const viewportHeight = this.viewportElement.offsetHeight;
  143. const compactHeight = slideSize.height * scale;
  144. const pageHeight = readerLayout === 'full' ? viewportHeight : compactHeight;
  145. // The height that needs to be scrolled between scroll triggers
  146. const scrollTriggerHeight = viewportHeight / 2;
  147. this.viewportElement.style.setProperty( '--page-height', pageHeight + 'px' );
  148. this.viewportElement.style.scrollSnapType = typeof config.readerScrollSnap === 'string' ?
  149. `y ${config.readerScrollSnap}` : '';
  150. const pageElements = Array.from( this.Reveal.getRevealElement().querySelectorAll( '.reader-page' ) );
  151. this.pages = pageElements.map( pageElement => {
  152. const page = {
  153. pageElement: pageElement,
  154. stickyElement: pageElement.querySelector( '.reader-page-sticky' ),
  155. slideElement: pageElement.querySelector( 'section' ),
  156. backgroundElement: pageElement.querySelector( '.slide-background' ),
  157. top: pageElement.offsetTop,
  158. scrollTriggers: [],
  159. };
  160. page.indexh = parseInt( page.slideElement.getAttribute( 'data-index-h' ), 10 );
  161. page.indexv = parseInt( page.slideElement.getAttribute( 'data-index-v' ), 10 );
  162. page.slideElement.style.width = slideSize.width + 'px';
  163. page.slideElement.style.height = config.center === true ? '' : slideSize.height + 'px';
  164. // Each fragment 'group' is an array containing one or more
  165. // fragments. Multiple fragments that appear at the same time
  166. // are part of the same group.
  167. page.fragments = this.Reveal.fragments.sort( pageElement.querySelectorAll( '.fragment:not(.disabled)' ) );
  168. page.fragmentGroups = this.Reveal.fragments.sort( pageElement.querySelectorAll( '.fragment' ), true );
  169. // Create scroll triggers that show/hide fragments
  170. if( page.fragmentGroups.length ) {
  171. const segmentSize = 1 / ( page.fragmentGroups.length + 1 );
  172. page.scrollTriggers.push(
  173. // Trigger for the initial state with no fragments visible
  174. { range: [ 0, segmentSize ], fragmentIndex: -1 },
  175. // Triggers for each fragment group
  176. ...page.fragmentGroups.map( ( fragments, i ) => ({
  177. range: [ segmentSize * ( i + 1 ), segmentSize * ( i + 2 ) ],
  178. fragmentIndex: i
  179. }))
  180. );
  181. }
  182. // Add scroll padding based on how many scroll triggers we have
  183. page.scrollPadding = scrollTriggerHeight * page.scrollTriggers.length;
  184. // In the compact layout, only slides with scroll triggers cover the
  185. // full viewport height. This helps avoid empty gaps before or after
  186. // a sticky slide.
  187. if( readerLayout === 'compact' && page.scrollTriggers.length > 0 ) {
  188. page.pageHeight = viewportHeight;
  189. page.pageElement.style.setProperty( '--page-height', viewportHeight + 'px' );
  190. }
  191. else {
  192. page.pageHeight = pageHeight;
  193. page.pageElement.style.removeProperty( '--page-height' );
  194. }
  195. page.pageElement.style.scrollSnapAlign = page.pageHeight < viewportHeight ? 'center' : 'start';
  196. // This variable is used to pad the height of our page in CSS
  197. page.pageElement.style.setProperty( '--page-scroll-padding', page.scrollPadding + 'px' );
  198. // The total height including scrollable space
  199. page.totalHeight = page.pageHeight + page.scrollPadding;
  200. page.bottom = page.top + page.totalHeight;
  201. // If this is a sticky page, stick it to the vertical center
  202. if( page.scrollTriggers.length > 0 ) {
  203. page.stickyElement.style.position = 'sticky';
  204. page.stickyElement.style.top = Math.max( ( viewportHeight - page.pageHeight ) / 2, 0 ) + 'px';
  205. // Make this page freeze at the vertical center of the viewport
  206. page.top -= ( viewportHeight - page.pageHeight ) / 2;
  207. }
  208. else {
  209. page.stickyElement.style.position = 'relative';
  210. }
  211. return page;
  212. } );
  213. this.createProgressBarSlides();
  214. }
  215. createProgressBarSlides() {
  216. this.progressBarInner.querySelectorAll( '.reader-progress-slide' ).forEach( slide => slide.remove() );
  217. const spacing = 2;
  218. const viewportHeight = this.viewportElement.offsetHeight;
  219. const scrollHeight = this.viewportElement.scrollHeight;
  220. this.progressBarHeight = this.progressBarInner.offsetHeight;
  221. this.playheadHeight = viewportHeight / scrollHeight * this.progressBarHeight;
  222. this.progressBarScrollableHeight = this.progressBarHeight - this.playheadHeight;
  223. this.progressBarPlayhead.style.height = this.playheadHeight - spacing + 'px';
  224. this.pages.forEach( page => {
  225. page.progressBarSlide = document.createElement( 'div' );
  226. page.progressBarSlide.className = 'reader-progress-slide';
  227. page.progressBarSlide.style.top = page.top / scrollHeight * this.progressBarHeight + 'px';
  228. page.progressBarSlide.style.height = page.totalHeight / scrollHeight * this.progressBarHeight - spacing + 'px';
  229. this.progressBarInner.appendChild( page.progressBarSlide );
  230. } );
  231. }
  232. layout() {
  233. if( this.isActive() ) {
  234. this.sync();
  235. this.onScroll();
  236. }
  237. }
  238. moveProgressBarTo( progress ) {
  239. this.progressBarPlayhead.style.transform = `translateY(${progress * this.progressBarScrollableHeight}px)`;
  240. this.pages.forEach( ( page ) => {
  241. page.progressBarSlide.classList.toggle( 'active', !!page.active );
  242. page.scrollTriggers.forEach( trigger => {
  243. // page.progressBarSlide.classList.toggle( 'active', !!trigger.active );
  244. } );
  245. } );
  246. }
  247. scrollToSlide( slideElement ) {
  248. if( !this.active ) {
  249. this.activatedCallbacks.push( () => this.scrollToSlide( slideElement ) );
  250. }
  251. else {
  252. slideElement.parentNode.scrollIntoView();
  253. }
  254. }
  255. onScroll() {
  256. const viewportHeight = this.viewportElement.offsetHeight;
  257. const scrollTop = this.viewportElement.scrollTop;
  258. // Find the page closest to the center of the viewport, this
  259. // is the page we want to focus and activate
  260. const activePage = this.pages.reduce( ( closestPage, page ) => {
  261. const distance = Math.abs( ( page.top + page.pageHeight / 2 ) - scrollTop - viewportHeight / 2 );
  262. return distance < closestPage.distance ? { page, distance } : closestPage;
  263. }, { page: this.pages[0], distance: Infinity } ).page;
  264. this.pages.forEach( ( page, pageIndex ) => {
  265. const isWithinPreloadRange = scrollTop + viewportHeight >= page.top - viewportHeight && scrollTop < page.top + page.bottom + viewportHeight;
  266. const isPartiallyVisible = scrollTop + viewportHeight >= page.top && scrollTop < page.top + page.bottom;
  267. // Preload content when it appears within range
  268. if( isWithinPreloadRange ) {
  269. if( !page.preloaded ) {
  270. page.preloaded = true;
  271. this.Reveal.slideContent.load( page.slideElement );
  272. }
  273. }
  274. else if( page.preloaded ) {
  275. page.preloaded = false;
  276. this.Reveal.slideContent.unload( page.slideElement );
  277. }
  278. // Activate the current page — there can only be one active page at
  279. // a time.
  280. if( page === activePage ) {
  281. if( !page.active ) {
  282. page.active = true;
  283. page.pageElement.classList.add( 'present' );
  284. page.slideElement.classList.add( 'present' );
  285. this.Reveal.setCurrentReaderPage( page.pageElement, page.indexh, page.indexv );
  286. this.Reveal.slideContent.startEmbeddedContent( page.slideElement );
  287. if( page.backgroundElement ) {
  288. this.Reveal.slideContent.startEmbeddedContent( page.backgroundElement );
  289. }
  290. }
  291. }
  292. // Deactivate previously active pages
  293. else if( page.active ) {
  294. page.active = false;
  295. page.pageElement.classList.remove( 'present' );
  296. page.slideElement.classList.remove( 'present' );
  297. this.Reveal.slideContent.stopEmbeddedContent( page.slideElement );
  298. if( page.backgroundElement ) {
  299. this.Reveal.slideContent.stopEmbeddedContent( page.backgroundElement );
  300. }
  301. }
  302. // Handle scroll freezing and triggers for slides in view
  303. if( isPartiallyVisible && page.totalHeight > page.pageHeight ) {
  304. let scrollProgress = ( scrollTop - page.top ) / page.scrollPadding;
  305. scrollProgress = Math.max( Math.min( scrollProgress, 1 ), 0 );
  306. page.scrollTriggers.forEach( trigger => {
  307. if( scrollProgress >= trigger.range[0] && scrollProgress < trigger.range[1] ) {
  308. if( !trigger.active ) {
  309. trigger.active = true;
  310. this.Reveal.fragments.update( trigger.fragmentIndex, page.fragments, page.slideElement );
  311. }
  312. }
  313. else {
  314. trigger.active = false;
  315. }
  316. } );
  317. }
  318. } );
  319. this.moveProgressBarTo( scrollTop / ( this.viewportElement.scrollHeight - viewportHeight ) );
  320. }
  321. get viewportElement() {
  322. return this.Reveal.getViewportElement();
  323. }
  324. }