reader.js 17 KB

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