scrollview.js 25 KB

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