scrollview.js 26 KB

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