scrollview.js 25 KB

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