scrollview.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. import { HORIZONTAL_SLIDES_SELECTOR, SLIDES_BACKGROUNDS_SELECTOR } from '../utils/constants.js'
  2. import { queryAll } from '../utils/util.js'
  3. const HIDE_SCROLLBAR_TIMEOUT = 500;
  4. const MAX_PROGRESS_SPACING = 4;
  5. const MIN_PROGRESS_SEGMENT_HEIGHT = 6;
  6. const MIN_PLAYHEAD_HEIGHT = 8;
  7. /**
  8. * The scroll view lets you read a reveal.js presentation
  9. * as a linear scrollable page.
  10. */
  11. export default class ScrollView {
  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 scroll view. 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 stateBeforeActivation = this.Reveal.getState();
  25. this.active = true;
  26. // Store the full presentation HTML so that we can restore it
  27. // when/if the scroll view is deactivated
  28. this.slideHTMLBeforeActivation = this.Reveal.getSlidesElement().innerHTML;
  29. const horizontalSlides = queryAll( this.Reveal.getRevealElement(), HORIZONTAL_SLIDES_SELECTOR );
  30. const slideBackgrounds = queryAll( this.Reveal.getRevealElement(), SLIDES_BACKGROUNDS_SELECTOR );
  31. this.viewportElement.classList.add( 'loading-scroll-mode', 'reveal-scroll' );
  32. let presentationBackground;
  33. const viewportStyles = window.getComputedStyle( this.viewportElement );
  34. if( viewportStyles && viewportStyles.background ) {
  35. presentationBackground = viewportStyles.background;
  36. }
  37. const pageElements = [];
  38. const pageContainer = horizontalSlides[0].parentNode;
  39. let previousSlide;
  40. // Creates a new page element and appends the given slide/bg
  41. // to it.
  42. const createPageElement = ( slide, h, v ) => {
  43. let contentContainer;
  44. // If this slide is part of an auto-animation sequence, we
  45. // group it under the same page element as the previous slide
  46. if( previousSlide && this.Reveal.shouldAutoAnimateBetween( previousSlide, slide ) ) {
  47. contentContainer = document.createElement( 'div' );
  48. contentContainer.className = 'scroll-page-content scroll-auto-animate-page';
  49. contentContainer.style.display = 'none';
  50. previousSlide.closest( '.scroll-page-content' ).parentNode.appendChild( contentContainer );
  51. }
  52. else {
  53. // Wrap the slide in a page element and hide its overflow
  54. // so that no page ever flows onto another
  55. const page = document.createElement( 'div' );
  56. page.className = 'scroll-page';
  57. pageElements.push( page );
  58. // Copy the presentation-wide background to each page
  59. if( slideBackgrounds && slideBackgrounds.length > h ) {
  60. const slideBackground = slideBackgrounds[h];
  61. const pageBackground = window.getComputedStyle( slideBackground );
  62. if( pageBackground && pageBackground.background ) {
  63. page.style.background = pageBackground.background;
  64. } else if( presentationBackground ) {
  65. page.style.background = presentationBackground;
  66. }
  67. } else if( presentationBackground ) {
  68. page.style.background = presentationBackground;
  69. }
  70. const stickyContainer = document.createElement( 'div' );
  71. stickyContainer.className = 'scroll-page-sticky';
  72. page.appendChild( stickyContainer );
  73. contentContainer = document.createElement( 'div' );
  74. contentContainer.className = 'scroll-page-content';
  75. stickyContainer.appendChild( contentContainer );
  76. }
  77. contentContainer.appendChild( slide );
  78. slide.classList.remove( 'past', 'future' );
  79. slide.setAttribute( 'data-index-h', h );
  80. slide.setAttribute( 'data-index-v', v );
  81. if( slide.slideBackgroundElement ) {
  82. slide.slideBackgroundElement.remove( 'past', 'future' );
  83. contentContainer.insertBefore( slide.slideBackgroundElement, slide );
  84. }
  85. previousSlide = slide;
  86. }
  87. // Slide and slide background layout
  88. horizontalSlides.forEach( ( horizontalSlide, h ) => {
  89. if( this.Reveal.isVerticalStack( horizontalSlide ) ) {
  90. horizontalSlide.querySelectorAll( 'section' ).forEach( ( verticalSlide, v ) => {
  91. createPageElement( verticalSlide, h, v );
  92. });
  93. }
  94. else {
  95. createPageElement( horizontalSlide, h, 0 );
  96. }
  97. }, this );
  98. this.createProgressBar();
  99. // Remove leftover stacks
  100. queryAll( this.Reveal.getRevealElement(), '.stack' ).forEach( stack => stack.remove() );
  101. // Add our newly created pages to the DOM
  102. pageElements.forEach( page => pageContainer.appendChild( page ) );
  103. // Re-run JS-based content layout after the slide is added to page DOM
  104. this.Reveal.slideContent.layout( this.Reveal.getSlidesElement() );
  105. this.Reveal.layout();
  106. this.Reveal.setState( stateBeforeActivation );
  107. this.activatedCallbacks.forEach( callback => callback() );
  108. this.activatedCallbacks = [];
  109. this.restoreScrollPosition();
  110. this.viewportElement.classList.remove( 'loading-scroll-mode' );
  111. this.viewportElement.addEventListener( 'scroll', this.onScroll, { passive: true } );
  112. }
  113. /**
  114. * Deactivates the scroll view and restores the standard slide-based
  115. * presentation.
  116. */
  117. deactivate() {
  118. if( !this.active ) return;
  119. const stateBeforeDeactivation = this.Reveal.getState();
  120. this.active = false;
  121. this.viewportElement.removeEventListener( 'scroll', this.onScroll );
  122. this.viewportElement.classList.remove( 'reveal-scroll' );
  123. this.removeProgressBar();
  124. this.Reveal.getSlidesElement().innerHTML = this.slideHTMLBeforeActivation;
  125. this.Reveal.sync();
  126. this.Reveal.setState( stateBeforeDeactivation );
  127. this.slideHTMLBeforeActivation = null;
  128. }
  129. toggle( override ) {
  130. if( typeof override === 'boolean' ) {
  131. override ? this.activate() : this.deactivate();
  132. }
  133. else {
  134. this.isActive() ? this.deactivate() : this.activate();
  135. }
  136. }
  137. /**
  138. * Checks if the scroll view is currently active.
  139. */
  140. isActive() {
  141. return this.active;
  142. }
  143. /**
  144. * Renders the progress bar component.
  145. */
  146. createProgressBar() {
  147. this.progressBar = document.createElement( 'div' );
  148. this.progressBar.className = 'scrollbar';
  149. this.progressBarInner = document.createElement( 'div' );
  150. this.progressBarInner.className = 'scrollbar-inner';
  151. this.progressBar.appendChild( this.progressBarInner );
  152. this.progressBarPlayhead = document.createElement( 'div' );
  153. this.progressBarPlayhead.className = 'scrollbar-playhead';
  154. this.progressBarInner.appendChild( this.progressBarPlayhead );
  155. this.viewportElement.insertBefore( this.progressBar, this.viewportElement.firstChild );
  156. const handleDocumentMouseMove = ( event ) => {
  157. let progress = ( event.clientY - this.progressBarInner.getBoundingClientRect().top ) / this.progressBarHeight;
  158. progress = Math.max( Math.min( progress, 1 ), 0 );
  159. this.viewportElement.scrollTop = progress * ( this.viewportElement.scrollHeight - this.viewportElement.offsetHeight );
  160. };
  161. const handleDocumentMouseUp = ( event ) => {
  162. this.draggingProgressBar = false;
  163. this.showProgressBar();
  164. document.removeEventListener( 'mousemove', handleDocumentMouseMove );
  165. document.removeEventListener( 'mouseup', handleDocumentMouseUp );
  166. };
  167. const handleMouseDown = ( event ) => {
  168. event.preventDefault();
  169. this.draggingProgressBar = true;
  170. document.addEventListener( 'mousemove', handleDocumentMouseMove );
  171. document.addEventListener( 'mouseup', handleDocumentMouseUp );
  172. handleDocumentMouseMove( event );
  173. };
  174. this.progressBarInner.addEventListener( 'mousedown', handleMouseDown );
  175. }
  176. removeProgressBar() {
  177. if( this.progressBar ) {
  178. this.progressBar.remove();
  179. this.progressBar = null;
  180. }
  181. }
  182. layout() {
  183. if( this.isActive() ) {
  184. this.syncPages();
  185. this.syncScrollPosition();
  186. }
  187. }
  188. /**
  189. * Updates our pages to match the latest configuration and
  190. * presentation size.
  191. */
  192. syncPages() {
  193. const config = this.Reveal.getConfig();
  194. const slideSize = this.Reveal.getComputedSlideSize( window.innerWidth, window.innerHeight );
  195. const scale = this.Reveal.getScale();
  196. const useCompactLayout = config.scrollLayout === 'compact';
  197. const viewportHeight = this.viewportElement.offsetHeight;
  198. const compactHeight = slideSize.height * scale;
  199. const pageHeight = useCompactLayout ? compactHeight : viewportHeight;
  200. // The height that needs to be scrolled between scroll triggers
  201. this.scrollTriggerHeight = useCompactLayout ? compactHeight : viewportHeight;
  202. this.viewportElement.style.setProperty( '--page-height', pageHeight + 'px' );
  203. this.viewportElement.style.scrollSnapType = typeof config.scrollSnap === 'string' ? `y ${config.scrollSnap}` : '';
  204. // This will hold all scroll triggers used to show/hide slides
  205. this.slideTriggers = [];
  206. const pageElements = Array.from( this.Reveal.getRevealElement().querySelectorAll( '.scroll-page' ) );
  207. this.pages = pageElements.map( pageElement => {
  208. const page = this.createPage({
  209. pageElement,
  210. slideElement: pageElement.querySelector( 'section' ),
  211. stickyElement: pageElement.querySelector( '.scroll-page-sticky' ),
  212. contentElement: pageElement.querySelector( '.scroll-page-content' ),
  213. backgroundElement: pageElement.querySelector( '.slide-background' ),
  214. autoAnimateElements: pageElement.querySelectorAll( '.scroll-auto-animate-page' ),
  215. autoAnimatePages: []
  216. });
  217. page.pageElement.style.setProperty( '--slide-height', config.center === true ? 'auto' : slideSize.height + 'px' );
  218. this.slideTriggers.push({
  219. page: page,
  220. activate: () => this.activatePage( page ),
  221. deactivate: () => this.deactivatePage( page )
  222. });
  223. // Create scroll triggers that show/hide fragments
  224. this.createFragmentTriggersForPage( page );
  225. // Create scroll triggers for triggering auto-animate steps
  226. if( page.autoAnimateElements.length > 0 ) {
  227. this.createAutoAnimateTriggersForPage( page );
  228. }
  229. let totalScrollTriggerCount = Math.max( page.scrollTriggers.length - 1, 0 );
  230. // Each auto-animate step may include its own scroll triggers
  231. // for fragments, ensure we count those as well
  232. totalScrollTriggerCount += page.autoAnimatePages.reduce( ( total, page ) => {
  233. return total + Math.max( page.scrollTriggers.length - 1, 0 );
  234. }, page.autoAnimatePages.length );
  235. // Clean up from previous renders
  236. page.pageElement.querySelectorAll( '.scroll-snap-point' ).forEach( el => el.remove() );
  237. // Create snap points for all scroll triggers
  238. // - Can't be absolute in FF
  239. // - Can't be 0-height in Safari
  240. // - Can't use snap-align on parent in Safari because then
  241. // inner triggers won't work
  242. for( let i = 0; i < totalScrollTriggerCount + 1; i++ ) {
  243. const triggerStick = document.createElement( 'div' );
  244. triggerStick.className = 'scroll-snap-point';
  245. triggerStick.style.height = this.scrollTriggerHeight + 'px';
  246. triggerStick.style.scrollSnapAlign = useCompactLayout ? 'center' : 'start';
  247. page.pageElement.appendChild( triggerStick );
  248. if( i === 0 ) {
  249. triggerStick.style.marginTop = -this.scrollTriggerHeight + 'px';
  250. }
  251. }
  252. // In the compact layout, only slides with scroll triggers cover the
  253. // full viewport height. This helps avoid empty gaps before or after
  254. // a sticky slide.
  255. if( useCompactLayout && page.scrollTriggers.length > 0 ) {
  256. page.pageHeight = viewportHeight;
  257. page.pageElement.style.setProperty( '--page-height', viewportHeight + 'px' );
  258. }
  259. else {
  260. page.pageHeight = pageHeight;
  261. page.pageElement.style.removeProperty( '--page-height' );
  262. }
  263. // Add scroll padding based on how many scroll triggers we have
  264. page.scrollPadding = this.scrollTriggerHeight * totalScrollTriggerCount;
  265. // The total height including scrollable space
  266. page.totalHeight = page.pageHeight + page.scrollPadding;
  267. // This is used to pad the height of our page in CSS
  268. page.pageElement.style.setProperty( '--page-scroll-padding', page.scrollPadding + 'px' );
  269. // If this is a sticky page, stick it to the vertical center
  270. if( totalScrollTriggerCount > 0 ) {
  271. page.stickyElement.style.position = 'sticky';
  272. page.stickyElement.style.top = Math.max( ( viewportHeight - page.pageHeight ) / 2, 0 ) + 'px';
  273. }
  274. else {
  275. page.stickyElement.style.position = 'relative';
  276. page.pageElement.style.scrollSnapAlign = page.pageHeight < viewportHeight ? 'center' : 'start';
  277. }
  278. return page;
  279. } );
  280. this.setTriggerRanges();
  281. /*
  282. console.log(this.slideTriggers.map( t => {
  283. return {
  284. range: `${t.range[0].toFixed(2)}-${t.range[1].toFixed(2)}`,
  285. triggers: t.page.scrollTriggers.map( t => {
  286. return `${t.range[0].toFixed(2)}-${t.range[1].toFixed(2)}`
  287. }).join( ', ' ),
  288. }
  289. }))
  290. */
  291. this.viewportElement.setAttribute( 'data-scrollbar', config.scrollProgress );
  292. if( config.scrollProgress && this.totalScrollTriggerCount > 1 ) {
  293. // Create the progress bar if it doesn't already exist
  294. if( !this.progressBar ) this.createProgressBar();
  295. this.syncProgressBar();
  296. }
  297. else {
  298. this.removeProgressBar();
  299. }
  300. }
  301. /**
  302. * Calculates and sets the scroll range for all of our scroll
  303. * triggers.
  304. */
  305. setTriggerRanges() {
  306. // Calculate the total number of scroll triggers
  307. this.totalScrollTriggerCount = this.slideTriggers.reduce( ( total, trigger ) => {
  308. return total + Math.max( trigger.page.scrollTriggers.length, 1 );
  309. }, 0 );
  310. let rangeStart = 0;
  311. // Calculate the scroll range of each scroll trigger on a scale
  312. // of 0-1
  313. this.slideTriggers.forEach( ( trigger, i ) => {
  314. trigger.range = [
  315. rangeStart,
  316. rangeStart + Math.max( trigger.page.scrollTriggers.length, 1 ) / this.totalScrollTriggerCount
  317. ];
  318. const scrollTriggerSegmentSize = ( trigger.range[1] - trigger.range[0] ) / trigger.page.scrollTriggers.length;
  319. // Set the range for each inner scroll trigger
  320. trigger.page.scrollTriggers.forEach( ( scrollTrigger, i ) => {
  321. scrollTrigger.range = [
  322. rangeStart + i * scrollTriggerSegmentSize,
  323. rangeStart + ( i + 1 ) * scrollTriggerSegmentSize
  324. ];
  325. } );
  326. rangeStart = trigger.range[1];
  327. } );
  328. }
  329. /**
  330. * Creates one scroll trigger for each fragments in the given page.
  331. *
  332. * @param {*} page
  333. */
  334. createFragmentTriggersForPage( page, slideElement ) {
  335. slideElement = slideElement || page.slideElement;
  336. // Each fragment 'group' is an array containing one or more
  337. // fragments. Multiple fragments that appear at the same time
  338. // are part of the same group.
  339. const fragmentGroups = this.Reveal.fragments.sort( slideElement.querySelectorAll( '.fragment' ), true );
  340. // Create scroll triggers that show/hide fragments
  341. if( fragmentGroups.length ) {
  342. page.fragments = this.Reveal.fragments.sort( slideElement.querySelectorAll( '.fragment:not(.disabled)' ) );
  343. page.scrollTriggers.push(
  344. // Trigger for the initial state with no fragments visible
  345. {
  346. activate: () => {
  347. this.Reveal.fragments.update( -1, page.fragments, slideElement );
  348. }
  349. }
  350. );
  351. // Triggers for each fragment group
  352. fragmentGroups.forEach( ( fragments, i ) => {
  353. page.scrollTriggers.push({
  354. activate: () => {
  355. this.Reveal.fragments.update( i, page.fragments, slideElement );
  356. }
  357. });
  358. } );
  359. }
  360. return page.scrollTriggers.length;
  361. }
  362. /**
  363. * Creates scroll triggers for the auto-animate steps in the
  364. * given page.
  365. *
  366. * @param {*} page
  367. */
  368. createAutoAnimateTriggersForPage( page ) {
  369. if( page.autoAnimateElements.length > 0 ) {
  370. // Triggers for each subsequent auto-animate slide
  371. this.slideTriggers.push( ...Array.from( page.autoAnimateElements ).map( ( autoAnimateElement, i ) => {
  372. let autoAnimatePage = this.createPage({
  373. slideElement: autoAnimateElement.querySelector( 'section' ),
  374. contentElement: autoAnimateElement,
  375. backgroundElement: autoAnimateElement.querySelector( '.slide-background' )
  376. });
  377. // Create fragment scroll triggers for the auto-animate slide
  378. this.createFragmentTriggersForPage( autoAnimatePage, autoAnimatePage.slideElement );
  379. page.autoAnimatePages.push( autoAnimatePage );
  380. // Return our slide trigger
  381. return {
  382. page: autoAnimatePage,
  383. activate: () => this.activatePage( autoAnimatePage ),
  384. deactivate: () => this.deactivatePage( autoAnimatePage )
  385. };
  386. }));
  387. }
  388. }
  389. /**
  390. * Helper method for creating a page definition and adding
  391. * required fields. A "page" is a slide or auto-animate step.
  392. */
  393. createPage( page ) {
  394. page.scrollTriggers = [];
  395. page.indexh = parseInt( page.slideElement.getAttribute( 'data-index-h' ), 10 );
  396. page.indexv = parseInt( page.slideElement.getAttribute( 'data-index-v' ), 10 );
  397. return page;
  398. }
  399. /**
  400. * Rerenders progress bar segments so that they match the current
  401. * reveal.js config and size.
  402. */
  403. syncProgressBar() {
  404. this.progressBarInner.querySelectorAll( '.scrollbar-slide' ).forEach( slide => slide.remove() );
  405. const scrollHeight = this.viewportElement.scrollHeight;
  406. const viewportHeight = this.viewportElement.offsetHeight;
  407. const viewportHeightFactor = viewportHeight / scrollHeight;
  408. this.progressBarHeight = this.progressBarInner.offsetHeight;
  409. this.playheadHeight = Math.max( viewportHeightFactor * this.progressBarHeight, MIN_PLAYHEAD_HEIGHT );
  410. this.progressBarScrollableHeight = this.progressBarHeight - this.playheadHeight;
  411. const progressSegmentHeight = viewportHeight / scrollHeight * this.progressBarHeight;
  412. const spacing = Math.min( progressSegmentHeight / 8, MAX_PROGRESS_SPACING );
  413. this.progressBarPlayhead.style.height = this.playheadHeight - spacing + 'px';
  414. // Don't show individual segments if they're too small
  415. if( progressSegmentHeight > MIN_PROGRESS_SEGMENT_HEIGHT ) {
  416. this.slideTriggers.forEach( slideTrigger => {
  417. const { page } = slideTrigger;
  418. // Visual representation of a slide
  419. page.progressBarSlide = document.createElement( 'div' );
  420. page.progressBarSlide.className = 'scrollbar-slide';
  421. page.progressBarSlide.style.top = slideTrigger.range[0] * this.progressBarHeight + 'px';
  422. page.progressBarSlide.style.height = ( slideTrigger.range[1] - slideTrigger.range[0] ) * this.progressBarHeight - spacing + 'px';
  423. page.progressBarSlide.classList.toggle( 'has-triggers', page.scrollTriggers.length > 0 );
  424. this.progressBarInner.appendChild( page.progressBarSlide );
  425. // Visual representations of each scroll trigger
  426. page.scrollTriggerElements = page.scrollTriggers.map( ( trigger, i ) => {
  427. const triggerElement = document.createElement( 'div' );
  428. triggerElement.className = 'scrollbar-trigger';
  429. triggerElement.style.top = ( trigger.range[0] - slideTrigger.range[0] ) * this.progressBarHeight + 'px';
  430. triggerElement.style.height = ( trigger.range[1] - trigger.range[0] ) * this.progressBarHeight - spacing + 'px';
  431. page.progressBarSlide.appendChild( triggerElement );
  432. if( i === 0 ) triggerElement.style.display = 'none';
  433. return triggerElement;
  434. } );
  435. } );
  436. }
  437. else {
  438. this.pages.forEach( page => page.progressBarSlide = null );
  439. }
  440. }
  441. /**
  442. * Reads the current scroll position and updates our active
  443. * trigger states accordingly.
  444. */
  445. syncScrollPosition() {
  446. const viewportHeight = this.viewportElement.offsetHeight;
  447. const viewportHeightFactor = viewportHeight / this.viewportElement.scrollHeight;
  448. const scrollTop = this.viewportElement.scrollTop;
  449. const scrollHeight = this.viewportElement.scrollHeight - viewportHeight
  450. const scrollProgress = Math.max( Math.min( scrollTop / scrollHeight, 1 ), 0 );
  451. const scrollProgressMid = Math.max( Math.min( ( scrollTop + viewportHeight / 2 ) / this.viewportElement.scrollHeight, 1 ), 0 );
  452. let activePage;
  453. this.slideTriggers.forEach( ( trigger ) => {
  454. const { page } = trigger;
  455. const shouldPreload = scrollProgress >= trigger.range[0] - viewportHeightFactor*2 &&
  456. scrollProgress <= trigger.range[1] + viewportHeightFactor*2;
  457. // Load slides that are within the preload range
  458. if( shouldPreload && !page.loaded ) {
  459. page.loaded = true;
  460. this.Reveal.slideContent.load( page.slideElement );
  461. }
  462. else if( page.loaded ) {
  463. page.loaded = false;
  464. this.Reveal.slideContent.unload( page.slideElement );
  465. }
  466. // If we're within this trigger range, activate it
  467. if( scrollProgress >= trigger.range[0] && scrollProgress <= trigger.range[1] ) {
  468. this.activateTrigger( trigger );
  469. activePage = trigger.page;
  470. }
  471. // .. otherwise deactivate
  472. else if( trigger.active ) {
  473. this.deactivateTrigger( trigger );
  474. }
  475. } );
  476. // Each page can have its own scroll triggers, check if any of those
  477. // need to be activated/deactivated
  478. if( activePage ) {
  479. activePage.scrollTriggers.forEach( ( trigger ) => {
  480. if( scrollProgressMid >= trigger.range[0] && scrollProgressMid <= trigger.range[1] ) {
  481. this.activateTrigger( trigger );
  482. }
  483. else if( trigger.active ) {
  484. this.deactivateTrigger( trigger );
  485. }
  486. } );
  487. }
  488. // Update our visual progress indication
  489. this.setProgressBarValue( scrollTop / ( this.viewportElement.scrollHeight - viewportHeight ) );
  490. }
  491. /**
  492. * Moves the progress bar playhead to the specified position.
  493. *
  494. * @param {number} progress 0-1
  495. */
  496. setProgressBarValue( progress ) {
  497. if( this.progressBar ) {
  498. this.progressBarPlayhead.style.transform = `translateY(${progress * this.progressBarScrollableHeight}px)`;
  499. this.getAllPages()
  500. .filter( page => page.progressBarSlide )
  501. .forEach( ( page ) => {
  502. page.progressBarSlide.classList.toggle( 'active', page.active === true );
  503. page.scrollTriggers.forEach( ( trigger, i ) => {
  504. page.scrollTriggerElements[i].classList.toggle( 'active', page.active === true && trigger.active === true );
  505. } );
  506. } );
  507. this.showProgressBar();
  508. }
  509. }
  510. /**
  511. * Show the progress bar and, if configured, automatically hide
  512. * it after a delay.
  513. */
  514. showProgressBar() {
  515. this.progressBar.classList.add( 'visible' );
  516. clearTimeout( this.hideProgressBarTimeout );
  517. if( this.Reveal.getConfig().scrollProgress === 'auto' && !this.draggingProgressBar ) {
  518. this.hideProgressBarTimeout = setTimeout( () => {
  519. if( this.progressBar ) {
  520. this.progressBar.classList.remove( 'visible' );
  521. }
  522. }, HIDE_SCROLLBAR_TIMEOUT );
  523. }
  524. }
  525. /**
  526. * Scroll to the previous page.
  527. */
  528. prev() {
  529. this.viewportElement.scrollTop -= this.scrollTriggerHeight;
  530. }
  531. /**
  532. * Scroll to the next page.
  533. */
  534. next() {
  535. this.viewportElement.scrollTop += this.scrollTriggerHeight;
  536. }
  537. /**
  538. * Scrolls the given slide element into view.
  539. *
  540. * @param {HTMLElement} slideElement
  541. */
  542. scrollToSlide( slideElement ) {
  543. // If the scroll view isn't active yet, queue this action
  544. if( !this.active ) {
  545. this.activatedCallbacks.push( () => this.scrollToSlide( slideElement ) );
  546. }
  547. else {
  548. // Find the trigger for this slide
  549. const trigger = this.getScrollTriggerBySlide( slideElement );
  550. if( trigger ) {
  551. // Use the trigger's range to calculate the scroll position
  552. this.viewportElement.scrollTop = trigger.range[0] * ( this.viewportElement.scrollHeight - this.viewportElement.offsetHeight );
  553. }
  554. }
  555. }
  556. /**
  557. * Persists the current scroll position to session storage
  558. * so that it can be restored.
  559. */
  560. storeScrollPosition() {
  561. clearTimeout( this.storeScrollPositionTimeout );
  562. this.storeScrollPositionTimeout = setTimeout( () => {
  563. sessionStorage.setItem( 'reveal-scroll-top', this.viewportElement.scrollTop );
  564. sessionStorage.setItem( 'reveal-scroll-origin', location.origin + location.pathname );
  565. this.storeScrollPositionTimeout = null;
  566. }, 50 );
  567. }
  568. /**
  569. * Restores the scroll position when a deck is reloader.
  570. */
  571. restoreScrollPosition() {
  572. const scrollPosition = sessionStorage.getItem( 'reveal-scroll-top' );
  573. const scrollOrigin = sessionStorage.getItem( 'reveal-scroll-origin' );
  574. if( scrollPosition && scrollOrigin === location.origin + location.pathname ) {
  575. this.viewportElement.scrollTop = parseInt( scrollPosition, 10 );
  576. }
  577. }
  578. /**
  579. * Activates the given page and starts its embedded content
  580. * if there is any.
  581. *
  582. * @param {object} page
  583. */
  584. activatePage( page ) {
  585. if( !page.active ) {
  586. page.active = true;
  587. const { slideElement, backgroundElement, contentElement, indexh, indexv } = page;
  588. contentElement.style.display = 'block';
  589. slideElement.classList.add( 'present' );
  590. if( backgroundElement ) {
  591. backgroundElement.classList.add( 'present' );
  592. }
  593. this.Reveal.setCurrentScrollPage( slideElement, indexh, indexv );
  594. this.Reveal.backgrounds.bubbleSlideContrastClassToElement( slideElement, this.viewportElement );
  595. // If this page is part of an auto-animation there will be one
  596. // content element per auto-animated page. We need to show the
  597. // current page and hide all others.
  598. Array.from( contentElement.parentNode.querySelectorAll( '.scroll-page-content' ) ).forEach( sibling => {
  599. if( sibling !== contentElement ) {
  600. sibling.style.display = 'none';
  601. }
  602. });
  603. }
  604. }
  605. /**
  606. * Deactivates the page after it has been visible.
  607. *
  608. * @param {object} page
  609. */
  610. deactivatePage( page ) {
  611. if( page.active ) {
  612. page.active = false;
  613. if( page.slideElement ) page.slideElement.classList.remove( 'present' );
  614. if( page.backgroundElement ) page.backgroundElement.classList.remove( 'present' );
  615. }
  616. }
  617. activateTrigger( trigger ) {
  618. if( !trigger.active ) {
  619. trigger.active = true;
  620. trigger.activate();
  621. }
  622. }
  623. deactivateTrigger( trigger ) {
  624. if( trigger.active ) {
  625. trigger.active = false;
  626. if( trigger.deactivate ) {
  627. trigger.deactivate();
  628. }
  629. }
  630. }
  631. /**
  632. * Retrieve a slide by its original h/v index (i.e. the indices the
  633. * slide had before being linearized).
  634. *
  635. * @param {number} h
  636. * @param {number} v
  637. * @returns {HTMLElement}
  638. */
  639. getSlideByIndices( h, v ) {
  640. const page = this.getAllPages().find( page => {
  641. return page.indexh === h && page.indexv === v;
  642. } );
  643. return page ? page.slideElement : null;
  644. }
  645. /**
  646. * Retrieve a list of all scroll triggers for the given slide
  647. * DOM element.
  648. *
  649. * @param {HTMLElement} slide
  650. * @returns {Array}
  651. */
  652. getScrollTriggerBySlide( slide ) {
  653. return this.slideTriggers.find( trigger => trigger.page.slideElement === slide );
  654. }
  655. /**
  656. * Get a list of all pages in the scroll view. This includes
  657. * both top-level slides and auto-animate steps.
  658. *
  659. * @returns {Array}
  660. */
  661. getAllPages() {
  662. return this.pages.flatMap( page => [page, ...(page.autoAnimatePages || [])] );
  663. }
  664. onScroll() {
  665. this.syncScrollPosition();
  666. this.storeScrollPosition();
  667. }
  668. get viewportElement() {
  669. return this.Reveal.getViewportElement();
  670. }
  671. }