You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2837 rivejä
73 KiB

  1. import SlideContent from './controllers/slidecontent.js'
  2. import SlideNumber from './controllers/slidenumber.js'
  3. import JumpToSlide from './controllers/jumptoslide.js'
  4. import Backgrounds from './controllers/backgrounds.js'
  5. import AutoAnimate from './controllers/autoanimate.js'
  6. import Fragments from './controllers/fragments.js'
  7. import Overview from './controllers/overview.js'
  8. import Keyboard from './controllers/keyboard.js'
  9. import Location from './controllers/location.js'
  10. import Controls from './controllers/controls.js'
  11. import Progress from './controllers/progress.js'
  12. import Pointer from './controllers/pointer.js'
  13. import Plugins from './controllers/plugins.js'
  14. import Print from './controllers/print.js'
  15. import Touch from './controllers/touch.js'
  16. import Focus from './controllers/focus.js'
  17. import Notes from './controllers/notes.js'
  18. import Playback from './components/playback.js'
  19. import defaultConfig from './config.js'
  20. import * as Util from './utils/util.js'
  21. import * as Device from './utils/device.js'
  22. import {
  23. SLIDES_SELECTOR,
  24. HORIZONTAL_SLIDES_SELECTOR,
  25. VERTICAL_SLIDES_SELECTOR,
  26. POST_MESSAGE_METHOD_BLACKLIST
  27. } from './utils/constants.js'
  28. // The reveal.js version
  29. export const VERSION = '4.5.0';
  30. /**
  31. * reveal.js
  32. * https://revealjs.com
  33. * MIT licensed
  34. *
  35. * Copyright (C) 2011-2022 Hakim El Hattab, https://hakim.se
  36. */
  37. export default function( revealElement, options ) {
  38. // Support initialization with no args, one arg
  39. // [options] or two args [revealElement, options]
  40. if( arguments.length < 2 ) {
  41. options = arguments[0];
  42. revealElement = document.querySelector( '.reveal' );
  43. }
  44. const Reveal = {};
  45. // Configuration defaults, can be overridden at initialization time
  46. let config = {},
  47. // Flags if reveal.js is loaded (has dispatched the 'ready' event)
  48. ready = false,
  49. // The horizontal and vertical index of the currently active slide
  50. indexh,
  51. indexv,
  52. // The previous and current slide HTML elements
  53. previousSlide,
  54. currentSlide,
  55. // Remember which directions that the user has navigated towards
  56. navigationHistory = {
  57. hasNavigatedHorizontally: false,
  58. hasNavigatedVertically: false
  59. },
  60. // Slides may have a data-state attribute which we pick up and apply
  61. // as a class to the body. This list contains the combined state of
  62. // all current slides.
  63. state = [],
  64. // The current scale of the presentation (see width/height config)
  65. scale = 1,
  66. // CSS transform that is currently applied to the slides container,
  67. // split into two groups
  68. slidesTransform = { layout: '', overview: '' },
  69. // Cached references to DOM elements
  70. dom = {},
  71. // Flags if the interaction event listeners are bound
  72. eventsAreBound = false,
  73. // The current slide transition state; idle or running
  74. transition = 'idle',
  75. // The current auto-slide duration
  76. autoSlide = 0,
  77. // Auto slide properties
  78. autoSlidePlayer,
  79. autoSlideTimeout = 0,
  80. autoSlideStartTime = -1,
  81. autoSlidePaused = false,
  82. // Controllers for different aspects of our presentation. They're
  83. // all given direct references to this Reveal instance since there
  84. // may be multiple presentations running in parallel.
  85. slideContent = new SlideContent( Reveal ),
  86. slideNumber = new SlideNumber( Reveal ),
  87. jumpToSlide = new JumpToSlide( Reveal ),
  88. autoAnimate = new AutoAnimate( Reveal ),
  89. backgrounds = new Backgrounds( Reveal ),
  90. fragments = new Fragments( Reveal ),
  91. overview = new Overview( Reveal ),
  92. keyboard = new Keyboard( Reveal ),
  93. location = new Location( Reveal ),
  94. controls = new Controls( Reveal ),
  95. progress = new Progress( Reveal ),
  96. pointer = new Pointer( Reveal ),
  97. plugins = new Plugins( Reveal ),
  98. print = new Print( Reveal ),
  99. focus = new Focus( Reveal ),
  100. touch = new Touch( Reveal ),
  101. notes = new Notes( Reveal );
  102. /**
  103. * Starts up the presentation.
  104. */
  105. function initialize( initOptions ) {
  106. if( !revealElement ) throw 'Unable to find presentation root (<div class="reveal">).';
  107. // Cache references to key DOM elements
  108. dom.wrapper = revealElement;
  109. dom.slides = revealElement.querySelector( '.slides' );
  110. if( !dom.slides ) throw 'Unable to find slides container (<div class="slides">).';
  111. // Compose our config object in order of increasing precedence:
  112. // 1. Default reveal.js options
  113. // 2. Options provided via Reveal.configure() prior to
  114. // initialization
  115. // 3. Options passed to the Reveal constructor
  116. // 4. Options passed to Reveal.initialize
  117. // 5. Query params
  118. config = { ...defaultConfig, ...config, ...options, ...initOptions, ...Util.getQueryHash() };
  119. setViewport();
  120. // Force a layout when the whole page, incl fonts, has loaded
  121. window.addEventListener( 'load', layout, false );
  122. // Register plugins and load dependencies, then move on to #start()
  123. plugins.load( config.plugins, config.dependencies ).then( start );
  124. return new Promise( resolve => Reveal.on( 'ready', resolve ) );
  125. }
  126. /**
  127. * Encase the presentation in a reveal.js viewport. The
  128. * extent of the viewport differs based on configuration.
  129. */
  130. function setViewport() {
  131. // Embedded decks use the reveal element as their viewport
  132. if( config.embedded === true ) {
  133. dom.viewport = Util.closest( revealElement, '.reveal-viewport' ) || revealElement;
  134. }
  135. // Full-page decks use the body as their viewport
  136. else {
  137. dom.viewport = document.body;
  138. document.documentElement.classList.add( 'reveal-full-page' );
  139. }
  140. dom.viewport.classList.add( 'reveal-viewport' );
  141. }
  142. /**
  143. * Starts up reveal.js by binding input events and navigating
  144. * to the current URL deeplink if there is one.
  145. */
  146. function start() {
  147. ready = true;
  148. // Remove slides hidden with data-visibility
  149. removeHiddenSlides();
  150. // Make sure we've got all the DOM elements we need
  151. setupDOM();
  152. // Listen to messages posted to this window
  153. setupPostMessage();
  154. // Prevent the slides from being scrolled out of view
  155. setupScrollPrevention();
  156. // Adds bindings for fullscreen mode
  157. setupFullscreen();
  158. // Resets all vertical slides so that only the first is visible
  159. resetVerticalSlides();
  160. // Updates the presentation to match the current configuration values
  161. configure();
  162. // Read the initial hash
  163. location.readURL();
  164. // Create slide backgrounds
  165. backgrounds.update( true );
  166. // Notify listeners that the presentation is ready but use a 1ms
  167. // timeout to ensure it's not fired synchronously after #initialize()
  168. setTimeout( () => {
  169. // Enable transitions now that we're loaded
  170. dom.slides.classList.remove( 'no-transition' );
  171. dom.wrapper.classList.add( 'ready' );
  172. dispatchEvent({
  173. type: 'ready',
  174. data: {
  175. indexh,
  176. indexv,
  177. currentSlide
  178. }
  179. });
  180. }, 1 );
  181. // Special setup and config is required when printing to PDF
  182. if( print.isPrintingPDF() ) {
  183. removeEventListeners();
  184. // The document needs to have loaded for the PDF layout
  185. // measurements to be accurate
  186. if( document.readyState === 'complete' ) {
  187. print.setupPDF();
  188. }
  189. else {
  190. window.addEventListener( 'load', () => {
  191. print.setupPDF();
  192. } );
  193. }
  194. }
  195. }
  196. /**
  197. * Removes all slides with data-visibility="hidden". This
  198. * is done right before the rest of the presentation is
  199. * initialized.
  200. *
  201. * If you want to show all hidden slides, initialize
  202. * reveal.js with showHiddenSlides set to true.
  203. */
  204. function removeHiddenSlides() {
  205. if( !config.showHiddenSlides ) {
  206. Util.queryAll( dom.wrapper, 'section[data-visibility="hidden"]' ).forEach( slide => {
  207. slide.parentNode.removeChild( slide );
  208. } );
  209. }
  210. }
  211. /**
  212. * Finds and stores references to DOM elements which are
  213. * required by the presentation. If a required element is
  214. * not found, it is created.
  215. */
  216. function setupDOM() {
  217. // Prevent transitions while we're loading
  218. dom.slides.classList.add( 'no-transition' );
  219. if( Device.isMobile ) {
  220. dom.wrapper.classList.add( 'no-hover' );
  221. }
  222. else {
  223. dom.wrapper.classList.remove( 'no-hover' );
  224. }
  225. backgrounds.render();
  226. slideNumber.render();
  227. jumpToSlide.render();
  228. controls.render();
  229. progress.render();
  230. notes.render();
  231. // Overlay graphic which is displayed during the paused mode
  232. dom.pauseOverlay = Util.createSingletonNode( dom.wrapper, 'div', 'pause-overlay', config.controls ? '<button class="resume-button">Resume presentation</button>' : null );
  233. dom.statusElement = createStatusElement();
  234. dom.wrapper.setAttribute( 'role', 'application' );
  235. }
  236. /**
  237. * Creates a hidden div with role aria-live to announce the
  238. * current slide content. Hide the div off-screen to make it
  239. * available only to Assistive Technologies.
  240. *
  241. * @return {HTMLElement}
  242. */
  243. function createStatusElement() {
  244. let statusElement = dom.wrapper.querySelector( '.aria-status' );
  245. if( !statusElement ) {
  246. statusElement = document.createElement( 'div' );
  247. statusElement.style.position = 'absolute';
  248. statusElement.style.height = '1px';
  249. statusElement.style.width = '1px';
  250. statusElement.style.overflow = 'hidden';
  251. statusElement.style.clip = 'rect( 1px, 1px, 1px, 1px )';
  252. statusElement.classList.add( 'aria-status' );
  253. statusElement.setAttribute( 'aria-live', 'polite' );
  254. statusElement.setAttribute( 'aria-atomic','true' );
  255. dom.wrapper.appendChild( statusElement );
  256. }
  257. return statusElement;
  258. }
  259. /**
  260. * Announces the given text to screen readers.
  261. */
  262. function announceStatus( value ) {
  263. dom.statusElement.textContent = value;
  264. }
  265. /**
  266. * Converts the given HTML element into a string of text
  267. * that can be announced to a screen reader. Hidden
  268. * elements are excluded.
  269. */
  270. function getStatusText( node ) {
  271. let text = '';
  272. // Text node
  273. if( node.nodeType === 3 ) {
  274. text += node.textContent;
  275. }
  276. // Element node
  277. else if( node.nodeType === 1 ) {
  278. let isAriaHidden = node.getAttribute( 'aria-hidden' );
  279. let isDisplayHidden = window.getComputedStyle( node )['display'] === 'none';
  280. if( isAriaHidden !== 'true' && !isDisplayHidden ) {
  281. Array.from( node.childNodes ).forEach( child => {
  282. text += getStatusText( child );
  283. } );
  284. }
  285. }
  286. text = text.trim();
  287. return text === '' ? '' : text + ' ';
  288. }
  289. /**
  290. * This is an unfortunate necessity. Some actions – such as
  291. * an input field being focused in an iframe or using the
  292. * keyboard to expand text selection beyond the bounds of
  293. * a slide – can trigger our content to be pushed out of view.
  294. * This scrolling can not be prevented by hiding overflow in
  295. * CSS (we already do) so we have to resort to repeatedly
  296. * checking if the slides have been offset :(
  297. */
  298. function setupScrollPrevention() {
  299. setInterval( () => {
  300. if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) {
  301. dom.wrapper.scrollTop = 0;
  302. dom.wrapper.scrollLeft = 0;
  303. }
  304. }, 1000 );
  305. }
  306. /**
  307. * After entering fullscreen we need to force a layout to
  308. * get our presentations to scale correctly. This behavior
  309. * is inconsistent across browsers but a force layout seems
  310. * to normalize it.
  311. */
  312. function setupFullscreen() {
  313. document.addEventListener( 'fullscreenchange', onFullscreenChange );
  314. document.addEventListener( 'webkitfullscreenchange', onFullscreenChange );
  315. }
  316. /**
  317. * Registers a listener to postMessage events, this makes it
  318. * possible to call all reveal.js API methods from another
  319. * window. For example:
  320. *
  321. * revealWindow.postMessage( JSON.stringify({
  322. * method: 'slide',
  323. * args: [ 2 ]
  324. * }), '*' );
  325. */
  326. function setupPostMessage() {
  327. if( config.postMessage ) {
  328. window.addEventListener( 'message', onPostMessage, false );
  329. }
  330. }
  331. /**
  332. * Applies the configuration settings from the config
  333. * object. May be called multiple times.
  334. *
  335. * @param {object} options
  336. */
  337. function configure( options ) {
  338. const oldConfig = { ...config }
  339. // New config options may be passed when this method
  340. // is invoked through the API after initialization
  341. if( typeof options === 'object' ) Util.extend( config, options );
  342. // Abort if reveal.js hasn't finished loading, config
  343. // changes will be applied automatically once ready
  344. if( Reveal.isReady() === false ) return;
  345. const numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length;
  346. // The transition is added as a class on the .reveal element
  347. dom.wrapper.classList.remove( oldConfig.transition );
  348. dom.wrapper.classList.add( config.transition );
  349. dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
  350. dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
  351. // Expose our configured slide dimensions as custom props
  352. dom.viewport.style.setProperty( '--slide-width', config.width + 'px' );
  353. dom.viewport.style.setProperty( '--slide-height', config.height + 'px' );
  354. if( config.shuffle ) {
  355. shuffle();
  356. }
  357. Util.toggleClass( dom.wrapper, 'embedded', config.embedded );
  358. Util.toggleClass( dom.wrapper, 'rtl', config.rtl );
  359. Util.toggleClass( dom.wrapper, 'center', config.center );
  360. // Exit the paused mode if it was configured off
  361. if( config.pause === false ) {
  362. resume();
  363. }
  364. // Iframe link previews
  365. if( config.previewLinks ) {
  366. enablePreviewLinks();
  367. disablePreviewLinks( '[data-preview-link=false]' );
  368. }
  369. else {
  370. disablePreviewLinks();
  371. enablePreviewLinks( '[data-preview-link]:not([data-preview-link=false])' );
  372. }
  373. // Reset all changes made by auto-animations
  374. autoAnimate.reset();
  375. // Remove existing auto-slide controls
  376. if( autoSlidePlayer ) {
  377. autoSlidePlayer.destroy();
  378. autoSlidePlayer = null;
  379. }
  380. // Generate auto-slide controls if needed
  381. if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable ) {
  382. autoSlidePlayer = new Playback( dom.wrapper, () => {
  383. return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 );
  384. } );
  385. autoSlidePlayer.on( 'click', onAutoSlidePlayerClick );
  386. autoSlidePaused = false;
  387. }
  388. // Add the navigation mode to the DOM so we can adjust styling
  389. if( config.navigationMode !== 'default' ) {
  390. dom.wrapper.setAttribute( 'data-navigation-mode', config.navigationMode );
  391. }
  392. else {
  393. dom.wrapper.removeAttribute( 'data-navigation-mode' );
  394. }
  395. notes.configure( config, oldConfig );
  396. focus.configure( config, oldConfig );
  397. pointer.configure( config, oldConfig );
  398. controls.configure( config, oldConfig );
  399. progress.configure( config, oldConfig );
  400. keyboard.configure( config, oldConfig );
  401. fragments.configure( config, oldConfig );
  402. slideNumber.configure( config, oldConfig );
  403. sync();
  404. }
  405. /**
  406. * Binds all event listeners.
  407. */
  408. function addEventListeners() {
  409. eventsAreBound = true;
  410. window.addEventListener( 'resize', onWindowResize, false );
  411. if( config.touch ) touch.bind();
  412. if( config.keyboard ) keyboard.bind();
  413. if( config.progress ) progress.bind();
  414. if( config.respondToHashChanges ) location.bind();
  415. controls.bind();
  416. focus.bind();
  417. dom.slides.addEventListener( 'click', onSlidesClicked, false );
  418. dom.slides.addEventListener( 'transitionend', onTransitionEnd, false );
  419. dom.pauseOverlay.addEventListener( 'click', resume, false );
  420. if( config.focusBodyOnPageVisibilityChange ) {
  421. document.addEventListener( 'visibilitychange', onPageVisibilityChange, false );
  422. }
  423. }
  424. /**
  425. * Unbinds all event listeners.
  426. */
  427. function removeEventListeners() {
  428. eventsAreBound = false;
  429. touch.unbind();
  430. focus.unbind();
  431. keyboard.unbind();
  432. controls.unbind();
  433. progress.unbind();
  434. location.unbind();
  435. window.removeEventListener( 'resize', onWindowResize, false );
  436. dom.slides.removeEventListener( 'click', onSlidesClicked, false );
  437. dom.slides.removeEventListener( 'transitionend', onTransitionEnd, false );
  438. dom.pauseOverlay.removeEventListener( 'click', resume, false );
  439. }
  440. /**
  441. * Uninitializes reveal.js by undoing changes made to the
  442. * DOM and removing all event listeners.
  443. */
  444. function destroy() {
  445. removeEventListeners();
  446. cancelAutoSlide();
  447. disablePreviewLinks();
  448. // Destroy controllers
  449. notes.destroy();
  450. focus.destroy();
  451. plugins.destroy();
  452. pointer.destroy();
  453. controls.destroy();
  454. progress.destroy();
  455. backgrounds.destroy();
  456. slideNumber.destroy();
  457. jumpToSlide.destroy();
  458. // Remove event listeners
  459. document.removeEventListener( 'fullscreenchange', onFullscreenChange );
  460. document.removeEventListener( 'webkitfullscreenchange', onFullscreenChange );
  461. document.removeEventListener( 'visibilitychange', onPageVisibilityChange, false );
  462. window.removeEventListener( 'message', onPostMessage, false );
  463. window.removeEventListener( 'load', layout, false );
  464. // Undo DOM changes
  465. if( dom.pauseOverlay ) dom.pauseOverlay.remove();
  466. if( dom.statusElement ) dom.statusElement.remove();
  467. document.documentElement.classList.remove( 'reveal-full-page' );
  468. dom.wrapper.classList.remove( 'ready', 'center', 'has-horizontal-slides', 'has-vertical-slides' );
  469. dom.wrapper.removeAttribute( 'data-transition-speed' );
  470. dom.wrapper.removeAttribute( 'data-background-transition' );
  471. dom.viewport.classList.remove( 'reveal-viewport' );
  472. dom.viewport.style.removeProperty( '--slide-width' );
  473. dom.viewport.style.removeProperty( '--slide-height' );
  474. dom.slides.style.removeProperty( 'width' );
  475. dom.slides.style.removeProperty( 'height' );
  476. dom.slides.style.removeProperty( 'zoom' );
  477. dom.slides.style.removeProperty( 'left' );
  478. dom.slides.style.removeProperty( 'top' );
  479. dom.slides.style.removeProperty( 'bottom' );
  480. dom.slides.style.removeProperty( 'right' );
  481. dom.slides.style.removeProperty( 'transform' );
  482. Array.from( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( slide => {
  483. slide.style.removeProperty( 'display' );
  484. slide.style.removeProperty( 'top' );
  485. slide.removeAttribute( 'hidden' );
  486. slide.removeAttribute( 'aria-hidden' );
  487. } );
  488. }
  489. /**
  490. * Adds a listener to one of our custom reveal.js events,
  491. * like slidechanged.
  492. */
  493. function on( type, listener, useCapture ) {
  494. revealElement.addEventListener( type, listener, useCapture );
  495. }
  496. /**
  497. * Unsubscribes from a reveal.js event.
  498. */
  499. function off( type, listener, useCapture ) {
  500. revealElement.removeEventListener( type, listener, useCapture );
  501. }
  502. /**
  503. * Applies CSS transforms to the slides container. The container
  504. * is transformed from two separate sources: layout and the overview
  505. * mode.
  506. *
  507. * @param {object} transforms
  508. */
  509. function transformSlides( transforms ) {
  510. // Pick up new transforms from arguments
  511. if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout;
  512. if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview;
  513. // Apply the transforms to the slides container
  514. if( slidesTransform.layout ) {
  515. Util.transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview );
  516. }
  517. else {
  518. Util.transformElement( dom.slides, slidesTransform.overview );
  519. }
  520. }
  521. /**
  522. * Dispatches an event of the specified type from the
  523. * reveal DOM element.
  524. */
  525. function dispatchEvent({ target=dom.wrapper, type, data, bubbles=true }) {
  526. let event = document.createEvent( 'HTMLEvents', 1, 2 );
  527. event.initEvent( type, bubbles, true );
  528. Util.extend( event, data );
  529. target.dispatchEvent( event );
  530. if( target === dom.wrapper ) {
  531. // If we're in an iframe, post each reveal.js event to the
  532. // parent window. Used by the notes plugin
  533. dispatchPostMessage( type );
  534. }
  535. return event;
  536. }
  537. /**
  538. * Dispatched a postMessage of the given type from our window.
  539. */
  540. function dispatchPostMessage( type, data ) {
  541. if( config.postMessageEvents && window.parent !== window.self ) {
  542. let message = {
  543. namespace: 'reveal',
  544. eventName: type,
  545. state: getState()
  546. };
  547. Util.extend( message, data );
  548. window.parent.postMessage( JSON.stringify( message ), '*' );
  549. }
  550. }
  551. /**
  552. * Bind preview frame links.
  553. *
  554. * @param {string} [selector=a] - selector for anchors
  555. */
  556. function enablePreviewLinks( selector = 'a' ) {
  557. Array.from( dom.wrapper.querySelectorAll( selector ) ).forEach( element => {
  558. if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
  559. element.addEventListener( 'click', onPreviewLinkClicked, false );
  560. }
  561. } );
  562. }
  563. /**
  564. * Unbind preview frame links.
  565. */
  566. function disablePreviewLinks( selector = 'a' ) {
  567. Array.from( dom.wrapper.querySelectorAll( selector ) ).forEach( element => {
  568. if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
  569. element.removeEventListener( 'click', onPreviewLinkClicked, false );
  570. }
  571. } );
  572. }
  573. /**
  574. * Opens a preview window for the target URL.
  575. *
  576. * @param {string} url - url for preview iframe src
  577. */
  578. function showPreview( url ) {
  579. closeOverlay();
  580. dom.overlay = document.createElement( 'div' );
  581. dom.overlay.classList.add( 'overlay' );
  582. dom.overlay.classList.add( 'overlay-preview' );
  583. dom.wrapper.appendChild( dom.overlay );
  584. dom.overlay.innerHTML =
  585. `<header>
  586. <a class="close" href="#"><span class="icon"></span></a>
  587. <a class="external" href="${url}" target="_blank"><span class="icon"></span></a>
  588. </header>
  589. <div class="spinner"></div>
  590. <div class="viewport">
  591. <iframe src="${url}"></iframe>
  592. <small class="viewport-inner">
  593. <span class="x-frame-error">Unable to load iframe. This is likely due to the site's policy (x-frame-options).</span>
  594. </small>
  595. </div>`;
  596. dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', event => {
  597. dom.overlay.classList.add( 'loaded' );
  598. }, false );
  599. dom.overlay.querySelector( '.close' ).addEventListener( 'click', event => {
  600. closeOverlay();
  601. event.preventDefault();
  602. }, false );
  603. dom.overlay.querySelector( '.external' ).addEventListener( 'click', event => {
  604. closeOverlay();
  605. }, false );
  606. }
  607. /**
  608. * Open or close help overlay window.
  609. *
  610. * @param {Boolean} [override] Flag which overrides the
  611. * toggle logic and forcibly sets the desired state. True means
  612. * help is open, false means it's closed.
  613. */
  614. function toggleHelp( override ){
  615. if( typeof override === 'boolean' ) {
  616. override ? showHelp() : closeOverlay();
  617. }
  618. else {
  619. if( dom.overlay ) {
  620. closeOverlay();
  621. }
  622. else {
  623. showHelp();
  624. }
  625. }
  626. }
  627. /**
  628. * Opens an overlay window with help material.
  629. */
  630. function showHelp() {
  631. if( config.help ) {
  632. closeOverlay();
  633. dom.overlay = document.createElement( 'div' );
  634. dom.overlay.classList.add( 'overlay' );
  635. dom.overlay.classList.add( 'overlay-help' );
  636. dom.wrapper.appendChild( dom.overlay );
  637. let html = '<p class="title">Keyboard Shortcuts</p><br/>';
  638. let shortcuts = keyboard.getShortcuts(),
  639. bindings = keyboard.getBindings();
  640. html += '<table><th>KEY</th><th>ACTION</th>';
  641. for( let key in shortcuts ) {
  642. html += `<tr><td>${key}</td><td>${shortcuts[ key ]}</td></tr>`;
  643. }
  644. // Add custom key bindings that have associated descriptions
  645. for( let binding in bindings ) {
  646. if( bindings[binding].key && bindings[binding].description ) {
  647. html += `<tr><td>${bindings[binding].key}</td><td>${bindings[binding].description}</td></tr>`;
  648. }
  649. }
  650. html += '</table>';
  651. dom.overlay.innerHTML = `
  652. <header>
  653. <a class="close" href="#"><span class="icon"></span></a>
  654. </header>
  655. <div class="viewport">
  656. <div class="viewport-inner">${html}</div>
  657. </div>
  658. `;
  659. dom.overlay.querySelector( '.close' ).addEventListener( 'click', event => {
  660. closeOverlay();
  661. event.preventDefault();
  662. }, false );
  663. }
  664. }
  665. /**
  666. * Closes any currently open overlay.
  667. */
  668. function closeOverlay() {
  669. if( dom.overlay ) {
  670. dom.overlay.parentNode.removeChild( dom.overlay );
  671. dom.overlay = null;
  672. return true;
  673. }
  674. return false;
  675. }
  676. /**
  677. * Applies JavaScript-controlled layout rules to the
  678. * presentation.
  679. */
  680. function layout() {
  681. if( dom.wrapper && !print.isPrintingPDF() ) {
  682. if( !config.disableLayout ) {
  683. // On some mobile devices '100vh' is taller than the visible
  684. // viewport which leads to part of the presentation being
  685. // cut off. To work around this we define our own '--vh' custom
  686. // property where 100x adds up to the correct height.
  687. //
  688. // https://css-tricks.com/the-trick-to-viewport-units-on-mobile/
  689. if( Device.isMobile && !config.embedded ) {
  690. document.documentElement.style.setProperty( '--vh', ( window.innerHeight * 0.01 ) + 'px' );
  691. }
  692. const size = getComputedSlideSize();
  693. const oldScale = scale;
  694. // Layout the contents of the slides
  695. layoutSlideContents( config.width, config.height );
  696. dom.slides.style.width = size.width + 'px';
  697. dom.slides.style.height = size.height + 'px';
  698. // Determine scale of content to fit within available space
  699. scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height );
  700. // Respect max/min scale settings
  701. scale = Math.max( scale, config.minScale );
  702. scale = Math.min( scale, config.maxScale );
  703. // Don't apply any scaling styles if scale is 1
  704. if( scale === 1 ) {
  705. dom.slides.style.zoom = '';
  706. dom.slides.style.left = '';
  707. dom.slides.style.top = '';
  708. dom.slides.style.bottom = '';
  709. dom.slides.style.right = '';
  710. transformSlides( { layout: '' } );
  711. }
  712. else {
  713. dom.slides.style.zoom = '';
  714. dom.slides.style.left = '50%';
  715. dom.slides.style.top = '50%';
  716. dom.slides.style.bottom = 'auto';
  717. dom.slides.style.right = 'auto';
  718. transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
  719. }
  720. // Select all slides, vertical and horizontal
  721. const slides = Array.from( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) );
  722. for( let i = 0, len = slides.length; i < len; i++ ) {
  723. const slide = slides[ i ];
  724. // Don't bother updating invisible slides
  725. if( slide.style.display === 'none' ) {
  726. continue;
  727. }
  728. if( config.center || slide.classList.contains( 'center' ) ) {
  729. // Vertical stacks are not centred since their section
  730. // children will be
  731. if( slide.classList.contains( 'stack' ) ) {
  732. slide.style.top = 0;
  733. }
  734. else {
  735. slide.style.top = Math.max( ( size.height - slide.scrollHeight ) / 2, 0 ) + 'px';
  736. }
  737. }
  738. else {
  739. slide.style.top = '';
  740. }
  741. }
  742. if( oldScale !== scale ) {
  743. dispatchEvent({
  744. type: 'resize',
  745. data: {
  746. oldScale,
  747. scale,
  748. size
  749. }
  750. });
  751. }
  752. }
  753. dom.viewport.style.setProperty( '--slide-scale', scale );
  754. progress.update();
  755. backgrounds.updateParallax();
  756. if( overview.isActive() ) {
  757. overview.update();
  758. }
  759. }
  760. }
  761. /**
  762. * Applies layout logic to the contents of all slides in
  763. * the presentation.
  764. *
  765. * @param {string|number} width
  766. * @param {string|number} height
  767. */
  768. function layoutSlideContents( width, height ) {
  769. // Handle sizing of elements with the 'r-stretch' class
  770. Util.queryAll( dom.slides, 'section > .stretch, section > .r-stretch' ).forEach( element => {
  771. // Determine how much vertical space we can use
  772. let remainingHeight = Util.getRemainingHeight( element, height );
  773. // Consider the aspect ratio of media elements
  774. if( /(img|video)/gi.test( element.nodeName ) ) {
  775. const nw = element.naturalWidth || element.videoWidth,
  776. nh = element.naturalHeight || element.videoHeight;
  777. const es = Math.min( width / nw, remainingHeight / nh );
  778. element.style.width = ( nw * es ) + 'px';
  779. element.style.height = ( nh * es ) + 'px';
  780. }
  781. else {
  782. element.style.width = width + 'px';
  783. element.style.height = remainingHeight + 'px';
  784. }
  785. } );
  786. }
  787. /**
  788. * Calculates the computed pixel size of our slides. These
  789. * values are based on the width and height configuration
  790. * options.
  791. *
  792. * @param {number} [presentationWidth=dom.wrapper.offsetWidth]
  793. * @param {number} [presentationHeight=dom.wrapper.offsetHeight]
  794. */
  795. function getComputedSlideSize( presentationWidth, presentationHeight ) {
  796. let width = config.width;
  797. let height = config.height;
  798. if( config.disableLayout ) {
  799. width = dom.slides.offsetWidth;
  800. height = dom.slides.offsetHeight;
  801. }
  802. const size = {
  803. // Slide size
  804. width: width,
  805. height: height,
  806. // Presentation size
  807. presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
  808. presentationHeight: presentationHeight || dom.wrapper.offsetHeight
  809. };
  810. // Reduce available space by margin
  811. size.presentationWidth -= ( size.presentationWidth * config.margin );
  812. size.presentationHeight -= ( size.presentationHeight * config.margin );
  813. // Slide width may be a percentage of available width
  814. if( typeof size.width === 'string' && /%$/.test( size.width ) ) {
  815. size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth;
  816. }
  817. // Slide height may be a percentage of available height
  818. if( typeof size.height === 'string' && /%$/.test( size.height ) ) {
  819. size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight;
  820. }
  821. return size;
  822. }
  823. /**
  824. * Stores the vertical index of a stack so that the same
  825. * vertical slide can be selected when navigating to and
  826. * from the stack.
  827. *
  828. * @param {HTMLElement} stack The vertical stack element
  829. * @param {string|number} [v=0] Index to memorize
  830. */
  831. function setPreviousVerticalIndex( stack, v ) {
  832. if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
  833. stack.setAttribute( 'data-previous-indexv', v || 0 );
  834. }
  835. }
  836. /**
  837. * Retrieves the vertical index which was stored using
  838. * #setPreviousVerticalIndex() or 0 if no previous index
  839. * exists.
  840. *
  841. * @param {HTMLElement} stack The vertical stack element
  842. */
  843. function getPreviousVerticalIndex( stack ) {
  844. if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
  845. // Prefer manually defined start-indexv
  846. const attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
  847. return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
  848. }
  849. return 0;
  850. }
  851. /**
  852. * Checks if the current or specified slide is vertical
  853. * (nested within another slide).
  854. *
  855. * @param {HTMLElement} [slide=currentSlide] The slide to check
  856. * orientation of
  857. * @return {Boolean}
  858. */
  859. function isVerticalSlide( slide = currentSlide ) {
  860. return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i );
  861. }
  862. /**
  863. * Returns true if we're on the last slide in the current
  864. * vertical stack.
  865. */
  866. function isLastVerticalSlide() {
  867. if( currentSlide && isVerticalSlide( currentSlide ) ) {
  868. // Does this slide have a next sibling?
  869. if( currentSlide.nextElementSibling ) return false;
  870. return true;
  871. }
  872. return false;
  873. }
  874. /**
  875. * Returns true if we're currently on the first slide in
  876. * the presentation.
  877. */
  878. function isFirstSlide() {
  879. return indexh === 0 && indexv === 0;
  880. }
  881. /**
  882. * Returns true if we're currently on the last slide in
  883. * the presenation. If the last slide is a stack, we only
  884. * consider this the last slide if it's at the end of the
  885. * stack.
  886. */
  887. function isLastSlide() {
  888. if( currentSlide ) {
  889. // Does this slide have a next sibling?
  890. if( currentSlide.nextElementSibling ) return false;
  891. // If it's vertical, does its parent have a next sibling?
  892. if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
  893. return true;
  894. }
  895. return false;
  896. }
  897. /**
  898. * Enters the paused mode which fades everything on screen to
  899. * black.
  900. */
  901. function pause() {
  902. if( config.pause ) {
  903. const wasPaused = dom.wrapper.classList.contains( 'paused' );
  904. cancelAutoSlide();
  905. dom.wrapper.classList.add( 'paused' );
  906. if( wasPaused === false ) {
  907. dispatchEvent({ type: 'paused' });
  908. }
  909. }
  910. }
  911. /**
  912. * Exits from the paused mode.
  913. */
  914. function resume() {
  915. const wasPaused = dom.wrapper.classList.contains( 'paused' );
  916. dom.wrapper.classList.remove( 'paused' );
  917. cueAutoSlide();
  918. if( wasPaused ) {
  919. dispatchEvent({ type: 'resumed' });
  920. }
  921. }
  922. /**
  923. * Toggles the paused mode on and off.
  924. */
  925. function togglePause( override ) {
  926. if( typeof override === 'boolean' ) {
  927. override ? pause() : resume();
  928. }
  929. else {
  930. isPaused() ? resume() : pause();
  931. }
  932. }
  933. /**
  934. * Checks if we are currently in the paused mode.
  935. *
  936. * @return {Boolean}
  937. */
  938. function isPaused() {
  939. return dom.wrapper.classList.contains( 'paused' );
  940. }
  941. /**
  942. * Toggles visibility of the jump-to-slide UI.
  943. */
  944. function toggleJumpToSlide( override ) {
  945. if( typeof override === 'boolean' ) {
  946. override ? jumpToSlide.show() : jumpToSlide.hide();
  947. }
  948. else {
  949. jumpToSlide.isVisible() ? jumpToSlide.hide() : jumpToSlide.show();
  950. }
  951. }
  952. /**
  953. * Toggles the auto slide mode on and off.
  954. *
  955. * @param {Boolean} [override] Flag which sets the desired state.
  956. * True means autoplay starts, false means it stops.
  957. */
  958. function toggleAutoSlide( override ) {
  959. if( typeof override === 'boolean' ) {
  960. override ? resumeAutoSlide() : pauseAutoSlide();
  961. }
  962. else {
  963. autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide();
  964. }
  965. }
  966. /**
  967. * Checks if the auto slide mode is currently on.
  968. *
  969. * @return {Boolean}
  970. */
  971. function isAutoSliding() {
  972. return !!( autoSlide && !autoSlidePaused );
  973. }
  974. /**
  975. * Steps from the current point in the presentation to the
  976. * slide which matches the specified horizontal and vertical
  977. * indices.
  978. *
  979. * @param {number} [h=indexh] Horizontal index of the target slide
  980. * @param {number} [v=indexv] Vertical index of the target slide
  981. * @param {number} [f] Index of a fragment within the
  982. * target slide to activate
  983. * @param {number} [origin] Origin for use in multimaster environments
  984. */
  985. function slide( h, v, f, origin ) {
  986. // Dispatch an event before the slide
  987. const slidechange = dispatchEvent({
  988. type: 'beforeslidechange',
  989. data: {
  990. indexh: h === undefined ? indexh : h,
  991. indexv: v === undefined ? indexv : v,
  992. origin
  993. }
  994. });
  995. // Abort if this slide change was prevented by an event listener
  996. if( slidechange.defaultPrevented ) return;
  997. // Remember where we were at before
  998. previousSlide = currentSlide;
  999. // Query all horizontal slides in the deck
  1000. const horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
  1001. // Abort if there are no slides
  1002. if( horizontalSlides.length === 0 ) return;
  1003. // If no vertical index is specified and the upcoming slide is a
  1004. // stack, resume at its previous vertical index
  1005. if( v === undefined && !overview.isActive() ) {
  1006. v = getPreviousVerticalIndex( horizontalSlides[ h ] );
  1007. }
  1008. // If we were on a vertical stack, remember what vertical index
  1009. // it was on so we can resume at the same position when returning
  1010. if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
  1011. setPreviousVerticalIndex( previousSlide.parentNode, indexv );
  1012. }
  1013. // Remember the state before this slide
  1014. const stateBefore = state.concat();
  1015. // Reset the state array
  1016. state.length = 0;
  1017. let indexhBefore = indexh || 0,
  1018. indexvBefore = indexv || 0;
  1019. // Activate and transition to the new slide
  1020. indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
  1021. indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
  1022. // Dispatch an event if the slide changed
  1023. let slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
  1024. // Ensure that the previous slide is never the same as the current
  1025. if( !slideChanged ) previousSlide = null;
  1026. // Find the current horizontal slide and any possible vertical slides
  1027. // within it
  1028. let currentHorizontalSlide = horizontalSlides[ indexh ],
  1029. currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
  1030. // Store references to the previous and current slides
  1031. currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
  1032. let autoAnimateTransition = false;
  1033. // Detect if we're moving between two auto-animated slides
  1034. if( slideChanged && previousSlide && currentSlide && !overview.isActive() ) {
  1035. // If this is an auto-animated transition, we disable the
  1036. // regular slide transition
  1037. //
  1038. // Note 20-03-2020:
  1039. // This needs to happen before we update slide visibility,
  1040. // otherwise transitions will still run in Safari.
  1041. if( previousSlide.hasAttribute( 'data-auto-animate' ) && currentSlide.hasAttribute( 'data-auto-animate' )
  1042. && previousSlide.getAttribute( 'data-auto-animate-id' ) === currentSlide.getAttribute( 'data-auto-animate-id' )
  1043. && !( ( indexh > indexhBefore || indexv > indexvBefore ) ? currentSlide : previousSlide ).hasAttribute( 'data-auto-animate-restart' ) ) {
  1044. autoAnimateTransition = true;
  1045. dom.slides.classList.add( 'disable-slide-transitions' );
  1046. }
  1047. transition = 'running';
  1048. }
  1049. // Update the visibility of slides now that the indices have changed
  1050. updateSlidesVisibility();
  1051. layout();
  1052. // Update the overview if it's currently active
  1053. if( overview.isActive() ) {
  1054. overview.update();
  1055. }
  1056. // Show fragment, if specified
  1057. if( typeof f !== 'undefined' ) {
  1058. fragments.goto( f );
  1059. }
  1060. // Solves an edge case where the previous slide maintains the
  1061. // 'present' class when navigating between adjacent vertical
  1062. // stacks
  1063. if( previousSlide && previousSlide !== currentSlide ) {
  1064. previousSlide.classList.remove( 'present' );
  1065. previousSlide.setAttribute( 'aria-hidden', 'true' );
  1066. // Reset all slides upon navigate to home
  1067. if( isFirstSlide() ) {
  1068. // Launch async task
  1069. setTimeout( () => {
  1070. getVerticalStacks().forEach( slide => {
  1071. setPreviousVerticalIndex( slide, 0 );
  1072. } );
  1073. }, 0 );
  1074. }
  1075. }
  1076. // Apply the new state
  1077. stateLoop: for( let i = 0, len = state.length; i < len; i++ ) {
  1078. // Check if this state existed on the previous slide. If it
  1079. // did, we will avoid adding it repeatedly
  1080. for( let j = 0; j < stateBefore.length; j++ ) {
  1081. if( stateBefore[j] === state[i] ) {
  1082. stateBefore.splice( j, 1 );
  1083. continue stateLoop;
  1084. }
  1085. }
  1086. dom.viewport.classList.add( state[i] );
  1087. // Dispatch custom event matching the state's name
  1088. dispatchEvent({ type: state[i] });
  1089. }
  1090. // Clean up the remains of the previous state
  1091. while( stateBefore.length ) {
  1092. dom.viewport.classList.remove( stateBefore.pop() );
  1093. }
  1094. if( slideChanged ) {
  1095. dispatchEvent({
  1096. type: 'slidechanged',
  1097. data: {
  1098. indexh,
  1099. indexv,
  1100. previousSlide,
  1101. currentSlide,
  1102. origin
  1103. }
  1104. });
  1105. }
  1106. // Handle embedded content
  1107. if( slideChanged || !previousSlide ) {
  1108. slideContent.stopEmbeddedContent( previousSlide );
  1109. slideContent.startEmbeddedContent( currentSlide );
  1110. }
  1111. // Announce the current slide contents to screen readers
  1112. // Use animation frame to prevent getComputedStyle in getStatusText
  1113. // from triggering layout mid-frame
  1114. requestAnimationFrame( () => {
  1115. announceStatus( getStatusText( currentSlide ) );
  1116. });
  1117. progress.update();
  1118. controls.update();
  1119. notes.update();
  1120. backgrounds.update();
  1121. backgrounds.updateParallax();
  1122. slideNumber.update();
  1123. fragments.update();
  1124. // Update the URL hash
  1125. location.writeURL();
  1126. cueAutoSlide();
  1127. // Auto-animation
  1128. if( autoAnimateTransition ) {
  1129. setTimeout( () => {
  1130. dom.slides.classList.remove( 'disable-slide-transitions' );
  1131. }, 0 );
  1132. if( config.autoAnimate ) {
  1133. // Run the auto-animation between our slides
  1134. autoAnimate.run( previousSlide, currentSlide );
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * Syncs the presentation with the current DOM. Useful
  1140. * when new slides or control elements are added or when
  1141. * the configuration has changed.
  1142. */
  1143. function sync() {
  1144. // Subscribe to input
  1145. removeEventListeners();
  1146. addEventListeners();
  1147. // Force a layout to make sure the current config is accounted for
  1148. layout();
  1149. // Reflect the current autoSlide value
  1150. autoSlide = config.autoSlide;
  1151. // Start auto-sliding if it's enabled
  1152. cueAutoSlide();
  1153. // Re-create all slide backgrounds
  1154. backgrounds.create();
  1155. // Write the current hash to the URL
  1156. location.writeURL();
  1157. if( config.sortFragmentsOnSync === true ) {
  1158. fragments.sortAll();
  1159. }
  1160. controls.update();
  1161. progress.update();
  1162. updateSlidesVisibility();
  1163. notes.update();
  1164. notes.updateVisibility();
  1165. backgrounds.update( true );
  1166. slideNumber.update();
  1167. slideContent.formatEmbeddedContent();
  1168. // Start or stop embedded content depending on global config
  1169. if( config.autoPlayMedia === false ) {
  1170. slideContent.stopEmbeddedContent( currentSlide, { unloadIframes: false } );
  1171. }
  1172. else {
  1173. slideContent.startEmbeddedContent( currentSlide );
  1174. }
  1175. if( overview.isActive() ) {
  1176. overview.layout();
  1177. }
  1178. }
  1179. /**
  1180. * Updates reveal.js to keep in sync with new slide attributes. For
  1181. * example, if you add a new `data-background-image` you can call
  1182. * this to have reveal.js render the new background image.
  1183. *
  1184. * Similar to #sync() but more efficient when you only need to
  1185. * refresh a specific slide.
  1186. *
  1187. * @param {HTMLElement} slide
  1188. */
  1189. function syncSlide( slide = currentSlide ) {
  1190. backgrounds.sync( slide );
  1191. fragments.sync( slide );
  1192. slideContent.load( slide );
  1193. backgrounds.update();
  1194. notes.update();
  1195. }
  1196. /**
  1197. * Resets all vertical slides so that only the first
  1198. * is visible.
  1199. */
  1200. function resetVerticalSlides() {
  1201. getHorizontalSlides().forEach( horizontalSlide => {
  1202. Util.queryAll( horizontalSlide, 'section' ).forEach( ( verticalSlide, y ) => {
  1203. if( y > 0 ) {
  1204. verticalSlide.classList.remove( 'present' );
  1205. verticalSlide.classList.remove( 'past' );
  1206. verticalSlide.classList.add( 'future' );
  1207. verticalSlide.setAttribute( 'aria-hidden', 'true' );
  1208. }
  1209. } );
  1210. } );
  1211. }
  1212. /**
  1213. * Randomly shuffles all slides in the deck.
  1214. */
  1215. function shuffle( slides = getHorizontalSlides() ) {
  1216. slides.forEach( ( slide, i ) => {
  1217. // Insert the slide next to a randomly picked sibling slide
  1218. // slide. This may cause the slide to insert before itself,
  1219. // but that's not an issue.
  1220. let beforeSlide = slides[ Math.floor( Math.random() * slides.length ) ];
  1221. if( beforeSlide.parentNode === slide.parentNode ) {
  1222. slide.parentNode.insertBefore( slide, beforeSlide );
  1223. }
  1224. // Randomize the order of vertical slides (if there are any)
  1225. let verticalSlides = slide.querySelectorAll( 'section' );
  1226. if( verticalSlides.length ) {
  1227. shuffle( verticalSlides );
  1228. }
  1229. } );
  1230. }
  1231. /**
  1232. * Updates one dimension of slides by showing the slide
  1233. * with the specified index.
  1234. *
  1235. * @param {string} selector A CSS selector that will fetch
  1236. * the group of slides we are working with
  1237. * @param {number} index The index of the slide that should be
  1238. * shown
  1239. *
  1240. * @return {number} The index of the slide that is now shown,
  1241. * might differ from the passed in index if it was out of
  1242. * bounds.
  1243. */
  1244. function updateSlides( selector, index ) {
  1245. // Select all slides and convert the NodeList result to
  1246. // an array
  1247. let slides = Util.queryAll( dom.wrapper, selector ),
  1248. slidesLength = slides.length;
  1249. let printMode = print.isPrintingPDF();
  1250. let loopedForwards = false;
  1251. let loopedBackwards = false;
  1252. if( slidesLength ) {
  1253. // Should the index loop?
  1254. if( config.loop ) {
  1255. if( index >= slidesLength ) loopedForwards = true;
  1256. index %= slidesLength;
  1257. if( index < 0 ) {
  1258. index = slidesLength + index;
  1259. loopedBackwards = true;
  1260. }
  1261. }
  1262. // Enforce max and minimum index bounds
  1263. index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
  1264. for( let i = 0; i < slidesLength; i++ ) {
  1265. let element = slides[i];
  1266. let reverse = config.rtl && !isVerticalSlide( element );
  1267. // Avoid .remove() with multiple args for IE11 support
  1268. element.classList.remove( 'past' );
  1269. element.classList.remove( 'present' );
  1270. element.classList.remove( 'future' );
  1271. // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
  1272. element.setAttribute( 'hidden', '' );
  1273. element.setAttribute( 'aria-hidden', 'true' );
  1274. // If this element contains vertical slides
  1275. if( element.querySelector( 'section' ) ) {
  1276. element.classList.add( 'stack' );
  1277. }
  1278. // If we're printing static slides, all slides are "present"
  1279. if( printMode ) {
  1280. element.classList.add( 'present' );
  1281. continue;
  1282. }
  1283. if( i < index ) {
  1284. // Any element previous to index is given the 'past' class
  1285. element.classList.add( reverse ? 'future' : 'past' );
  1286. if( config.fragments ) {
  1287. // Show all fragments in prior slides
  1288. showFragmentsIn( element );
  1289. }
  1290. }
  1291. else if( i > index ) {
  1292. // Any element subsequent to index is given the 'future' class
  1293. element.classList.add( reverse ? 'past' : 'future' );
  1294. if( config.fragments ) {
  1295. // Hide all fragments in future slides
  1296. hideFragmentsIn( element );
  1297. }
  1298. }
  1299. // Update the visibility of fragments when a presentation loops
  1300. // in either direction
  1301. else if( i === index && config.fragments ) {
  1302. if( loopedForwards ) {
  1303. hideFragmentsIn( element );
  1304. }
  1305. else if( loopedBackwards ) {
  1306. showFragmentsIn( element );
  1307. }
  1308. }
  1309. }
  1310. let slide = slides[index];
  1311. let wasPresent = slide.classList.contains( 'present' );
  1312. // Mark the current slide as present
  1313. slide.classList.add( 'present' );
  1314. slide.removeAttribute( 'hidden' );
  1315. slide.removeAttribute( 'aria-hidden' );
  1316. if( !wasPresent ) {
  1317. // Dispatch an event indicating the slide is now visible
  1318. dispatchEvent({
  1319. target: slide,
  1320. type: 'visible',
  1321. bubbles: false
  1322. });
  1323. }
  1324. // If this slide has a state associated with it, add it
  1325. // onto the current state of the deck
  1326. let slideState = slide.getAttribute( 'data-state' );
  1327. if( slideState ) {
  1328. state = state.concat( slideState.split( ' ' ) );
  1329. }
  1330. }
  1331. else {
  1332. // Since there are no slides we can't be anywhere beyond the
  1333. // zeroth index
  1334. index = 0;
  1335. }
  1336. return index;
  1337. }
  1338. /**
  1339. * Shows all fragment elements within the given contaienr.
  1340. */
  1341. function showFragmentsIn( container ) {
  1342. Util.queryAll( container, '.fragment' ).forEach( fragment => {
  1343. fragment.classList.add( 'visible' );
  1344. fragment.classList.remove( 'current-fragment' );
  1345. } );
  1346. }
  1347. /**
  1348. * Hides all fragment elements within the given contaienr.
  1349. */
  1350. function hideFragmentsIn( container ) {
  1351. Util.queryAll( container, '.fragment.visible' ).forEach( fragment => {
  1352. fragment.classList.remove( 'visible', 'current-fragment' );
  1353. } );
  1354. }
  1355. /**
  1356. * Optimization method; hide all slides that are far away
  1357. * from the present slide.
  1358. */
  1359. function updateSlidesVisibility() {
  1360. // Select all slides and convert the NodeList result to
  1361. // an array
  1362. let horizontalSlides = getHorizontalSlides(),
  1363. horizontalSlidesLength = horizontalSlides.length,
  1364. distanceX,
  1365. distanceY;
  1366. if( horizontalSlidesLength && typeof indexh !== 'undefined' ) {
  1367. // The number of steps away from the present slide that will
  1368. // be visible
  1369. let viewDistance = overview.isActive() ? 10 : config.viewDistance;
  1370. // Shorten the view distance on devices that typically have
  1371. // less resources
  1372. if( Device.isMobile ) {
  1373. viewDistance = overview.isActive() ? 6 : config.mobileViewDistance;
  1374. }
  1375. // All slides need to be visible when exporting to PDF
  1376. if( print.isPrintingPDF() ) {
  1377. viewDistance = Number.MAX_VALUE;
  1378. }
  1379. for( let x = 0; x < horizontalSlidesLength; x++ ) {
  1380. let horizontalSlide = horizontalSlides[x];
  1381. let verticalSlides = Util.queryAll( horizontalSlide, 'section' ),
  1382. verticalSlidesLength = verticalSlides.length;
  1383. // Determine how far away this slide is from the present
  1384. distanceX = Math.abs( ( indexh || 0 ) - x ) || 0;
  1385. // If the presentation is looped, distance should measure
  1386. // 1 between the first and last slides
  1387. if( config.loop ) {
  1388. distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
  1389. }
  1390. // Show the horizontal slide if it's within the view distance
  1391. if( distanceX < viewDistance ) {
  1392. slideContent.load( horizontalSlide );
  1393. }
  1394. else {
  1395. slideContent.unload( horizontalSlide );
  1396. }
  1397. if( verticalSlidesLength ) {
  1398. let oy = getPreviousVerticalIndex( horizontalSlide );
  1399. for( let y = 0; y < verticalSlidesLength; y++ ) {
  1400. let verticalSlide = verticalSlides[y];
  1401. distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy );
  1402. if( distanceX + distanceY < viewDistance ) {
  1403. slideContent.load( verticalSlide );
  1404. }
  1405. else {
  1406. slideContent.unload( verticalSlide );
  1407. }
  1408. }
  1409. }
  1410. }
  1411. // Flag if there are ANY vertical slides, anywhere in the deck
  1412. if( hasVerticalSlides() ) {
  1413. dom.wrapper.classList.add( 'has-vertical-slides' );
  1414. }
  1415. else {
  1416. dom.wrapper.classList.remove( 'has-vertical-slides' );
  1417. }
  1418. // Flag if there are ANY horizontal slides, anywhere in the deck
  1419. if( hasHorizontalSlides() ) {
  1420. dom.wrapper.classList.add( 'has-horizontal-slides' );
  1421. }
  1422. else {
  1423. dom.wrapper.classList.remove( 'has-horizontal-slides' );
  1424. }
  1425. }
  1426. }
  1427. /**
  1428. * Determine what available routes there are for navigation.
  1429. *
  1430. * @return {{left: boolean, right: boolean, up: boolean, down: boolean}}
  1431. */
  1432. function availableRoutes({ includeFragments = false } = {}) {
  1433. let horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
  1434. verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
  1435. let routes = {
  1436. left: indexh > 0,
  1437. right: indexh < horizontalSlides.length - 1,
  1438. up: indexv > 0,
  1439. down: indexv < verticalSlides.length - 1
  1440. };
  1441. // Looped presentations can always be navigated as long as
  1442. // there are slides available
  1443. if( config.loop ) {
  1444. if( horizontalSlides.length > 1 ) {
  1445. routes.left = true;
  1446. routes.right = true;
  1447. }
  1448. if( verticalSlides.length > 1 ) {
  1449. routes.up = true;
  1450. routes.down = true;
  1451. }
  1452. }
  1453. if ( horizontalSlides.length > 1 && config.navigationMode === 'linear' ) {
  1454. routes.right = routes.right || routes.down;
  1455. routes.left = routes.left || routes.up;
  1456. }
  1457. // If includeFragments is set, a route will be considered
  1458. // available if either a slid OR fragment is available in
  1459. // the given direction
  1460. if( includeFragments === true ) {
  1461. let fragmentRoutes = fragments.availableRoutes();
  1462. routes.left = routes.left || fragmentRoutes.prev;
  1463. routes.up = routes.up || fragmentRoutes.prev;
  1464. routes.down = routes.down || fragmentRoutes.next;
  1465. routes.right = routes.right || fragmentRoutes.next;
  1466. }
  1467. // Reverse horizontal controls for rtl
  1468. if( config.rtl ) {
  1469. let left = routes.left;
  1470. routes.left = routes.right;
  1471. routes.right = left;
  1472. }
  1473. return routes;
  1474. }
  1475. /**
  1476. * Returns the number of past slides. This can be used as a global
  1477. * flattened index for slides.
  1478. *
  1479. * @param {HTMLElement} [slide=currentSlide] The slide we're counting before
  1480. *
  1481. * @return {number} Past slide count
  1482. */
  1483. function getSlidePastCount( slide = currentSlide ) {
  1484. let horizontalSlides = getHorizontalSlides();
  1485. // The number of past slides
  1486. let pastCount = 0;
  1487. // Step through all slides and count the past ones
  1488. mainLoop: for( let i = 0; i < horizontalSlides.length; i++ ) {
  1489. let horizontalSlide = horizontalSlides[i];
  1490. let verticalSlides = horizontalSlide.querySelectorAll( 'section' );
  1491. for( let j = 0; j < verticalSlides.length; j++ ) {
  1492. // Stop as soon as we arrive at the present
  1493. if( verticalSlides[j] === slide ) {
  1494. break mainLoop;
  1495. }
  1496. // Don't count slides with the "uncounted" class
  1497. if( verticalSlides[j].dataset.visibility !== 'uncounted' ) {
  1498. pastCount++;
  1499. }
  1500. }
  1501. // Stop as soon as we arrive at the present
  1502. if( horizontalSlide === slide ) {
  1503. break;
  1504. }
  1505. // Don't count the wrapping section for vertical slides and
  1506. // slides marked as uncounted
  1507. if( horizontalSlide.classList.contains( 'stack' ) === false && horizontalSlide.dataset.visibility !== 'uncounted' ) {
  1508. pastCount++;
  1509. }
  1510. }
  1511. return pastCount;
  1512. }
  1513. /**
  1514. * Returns a value ranging from 0-1 that represents
  1515. * how far into the presentation we have navigated.
  1516. *
  1517. * @return {number}
  1518. */
  1519. function getProgress() {
  1520. // The number of past and total slides
  1521. let totalCount = getTotalSlides();
  1522. let pastCount = getSlidePastCount();
  1523. if( currentSlide ) {
  1524. let allFragments = currentSlide.querySelectorAll( '.fragment' );
  1525. // If there are fragments in the current slide those should be
  1526. // accounted for in the progress.
  1527. if( allFragments.length > 0 ) {
  1528. let visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
  1529. // This value represents how big a portion of the slide progress
  1530. // that is made up by its fragments (0-1)
  1531. let fragmentWeight = 0.9;
  1532. // Add fragment progress to the past slide count
  1533. pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight;
  1534. }
  1535. }
  1536. return Math.min( pastCount / ( totalCount - 1 ), 1 );
  1537. }
  1538. /**
  1539. * Retrieves the h/v location and fragment of the current,
  1540. * or specified, slide.
  1541. *
  1542. * @param {HTMLElement} [slide] If specified, the returned
  1543. * index will be for this slide rather than the currently
  1544. * active one
  1545. *
  1546. * @return {{h: number, v: number, f: number}}
  1547. */
  1548. function getIndices( slide ) {
  1549. // By default, return the current indices
  1550. let h = indexh,
  1551. v = indexv,
  1552. f;
  1553. // If a slide is specified, return the indices of that slide
  1554. if( slide ) {
  1555. let isVertical = isVerticalSlide( slide );
  1556. let slideh = isVertical ? slide.parentNode : slide;
  1557. // Select all horizontal slides
  1558. let horizontalSlides = getHorizontalSlides();
  1559. // Now that we know which the horizontal slide is, get its index
  1560. h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
  1561. // Assume we're not vertical
  1562. v = undefined;
  1563. // If this is a vertical slide, grab the vertical index
  1564. if( isVertical ) {
  1565. v = Math.max( Util.queryAll( slide.parentNode, 'section' ).indexOf( slide ), 0 );
  1566. }
  1567. }
  1568. if( !slide && currentSlide ) {
  1569. let hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
  1570. if( hasFragments ) {
  1571. let currentFragment = currentSlide.querySelector( '.current-fragment' );
  1572. if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) {
  1573. f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 );
  1574. }
  1575. else {
  1576. f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1;
  1577. }
  1578. }
  1579. }
  1580. return { h, v, f };
  1581. }
  1582. /**
  1583. * Retrieves all slides in this presentation.
  1584. */
  1585. function getSlides() {
  1586. return Util.queryAll( dom.wrapper, SLIDES_SELECTOR + ':not(.stack):not([data-visibility="uncounted"])' );
  1587. }
  1588. /**
  1589. * Returns a list of all horizontal slides in the deck. Each
  1590. * vertical stack is included as one horizontal slide in the
  1591. * resulting array.
  1592. */
  1593. function getHorizontalSlides() {
  1594. return Util.queryAll( dom.wrapper, HORIZONTAL_SLIDES_SELECTOR );
  1595. }
  1596. /**
  1597. * Returns all vertical slides that exist within this deck.
  1598. */
  1599. function getVerticalSlides() {
  1600. return Util.queryAll( dom.wrapper, '.slides>section>section' );
  1601. }
  1602. /**
  1603. * Returns all vertical stacks (each stack can contain multiple slides).
  1604. */
  1605. function getVerticalStacks() {
  1606. return Util.queryAll( dom.wrapper, HORIZONTAL_SLIDES_SELECTOR + '.stack');
  1607. }
  1608. /**
  1609. * Returns true if there are at least two horizontal slides.
  1610. */
  1611. function hasHorizontalSlides() {
  1612. return getHorizontalSlides().length > 1;
  1613. }
  1614. /**
  1615. * Returns true if there are at least two vertical slides.
  1616. */
  1617. function hasVerticalSlides() {
  1618. return getVerticalSlides().length > 1;
  1619. }
  1620. /**
  1621. * Returns an array of objects where each object represents the
  1622. * attributes on its respective slide.
  1623. */
  1624. function getSlidesAttributes() {
  1625. return getSlides().map( slide => {
  1626. let attributes = {};
  1627. for( let i = 0; i < slide.attributes.length; i++ ) {
  1628. let attribute = slide.attributes[ i ];
  1629. attributes[ attribute.name ] = attribute.value;
  1630. }
  1631. return attributes;
  1632. } );
  1633. }
  1634. /**
  1635. * Retrieves the total number of slides in this presentation.
  1636. *
  1637. * @return {number}
  1638. */
  1639. function getTotalSlides() {
  1640. return getSlides().length;
  1641. }
  1642. /**
  1643. * Returns the slide element matching the specified index.
  1644. *
  1645. * @return {HTMLElement}
  1646. */
  1647. function getSlide( x, y ) {
  1648. let horizontalSlide = getHorizontalSlides()[ x ];
  1649. let verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
  1650. if( verticalSlides && verticalSlides.length && typeof y === 'number' ) {
  1651. return verticalSlides ? verticalSlides[ y ] : undefined;
  1652. }
  1653. return horizontalSlide;
  1654. }
  1655. /**
  1656. * Returns the background element for the given slide.
  1657. * All slides, even the ones with no background properties
  1658. * defined, have a background element so as long as the
  1659. * index is valid an element will be returned.
  1660. *
  1661. * @param {mixed} x Horizontal background index OR a slide
  1662. * HTML element
  1663. * @param {number} y Vertical background index
  1664. * @return {(HTMLElement[]|*)}
  1665. */
  1666. function getSlideBackground( x, y ) {
  1667. let slide = typeof x === 'number' ? getSlide( x, y ) : x;
  1668. if( slide ) {
  1669. return slide.slideBackgroundElement;
  1670. }
  1671. return undefined;
  1672. }
  1673. /**
  1674. * Retrieves the current state of the presentation as
  1675. * an object. This state can then be restored at any
  1676. * time.
  1677. *
  1678. * @return {{indexh: number, indexv: number, indexf: number, paused: boolean, overview: boolean}}
  1679. */
  1680. function getState() {
  1681. let indices = getIndices();
  1682. return {
  1683. indexh: indices.h,
  1684. indexv: indices.v,
  1685. indexf: indices.f,
  1686. paused: isPaused(),
  1687. overview: overview.isActive()
  1688. };
  1689. }
  1690. /**
  1691. * Restores the presentation to the given state.
  1692. *
  1693. * @param {object} state As generated by getState()
  1694. * @see {@link getState} generates the parameter `state`
  1695. */
  1696. function setState( state ) {
  1697. if( typeof state === 'object' ) {
  1698. slide( Util.deserialize( state.indexh ), Util.deserialize( state.indexv ), Util.deserialize( state.indexf ) );
  1699. let pausedFlag = Util.deserialize( state.paused ),
  1700. overviewFlag = Util.deserialize( state.overview );
  1701. if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
  1702. togglePause( pausedFlag );
  1703. }
  1704. if( typeof overviewFlag === 'boolean' && overviewFlag !== overview.isActive() ) {
  1705. overview.toggle( overviewFlag );
  1706. }
  1707. }
  1708. }
  1709. /**
  1710. * Cues a new automated slide if enabled in the config.
  1711. */
  1712. function cueAutoSlide() {
  1713. cancelAutoSlide();
  1714. if( currentSlide && config.autoSlide !== false ) {
  1715. let fragment = currentSlide.querySelector( '.current-fragment[data-autoslide]' );
  1716. let fragmentAutoSlide = fragment ? fragment.getAttribute( 'data-autoslide' ) : null;
  1717. let parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
  1718. let slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
  1719. // Pick value in the following priority order:
  1720. // 1. Current fragment's data-autoslide
  1721. // 2. Current slide's data-autoslide
  1722. // 3. Parent slide's data-autoslide
  1723. // 4. Global autoSlide setting
  1724. if( fragmentAutoSlide ) {
  1725. autoSlide = parseInt( fragmentAutoSlide, 10 );
  1726. }
  1727. else if( slideAutoSlide ) {
  1728. autoSlide = parseInt( slideAutoSlide, 10 );
  1729. }
  1730. else if( parentAutoSlide ) {
  1731. autoSlide = parseInt( parentAutoSlide, 10 );
  1732. }
  1733. else {
  1734. autoSlide = config.autoSlide;
  1735. // If there are media elements with data-autoplay,
  1736. // automatically set the autoSlide duration to the
  1737. // length of that media. Not applicable if the slide
  1738. // is divided up into fragments.
  1739. // playbackRate is accounted for in the duration.
  1740. if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) {
  1741. Util.queryAll( currentSlide, 'video, audio' ).forEach( el => {
  1742. if( el.hasAttribute( 'data-autoplay' ) ) {
  1743. if( autoSlide && (el.duration * 1000 / el.playbackRate ) > autoSlide ) {
  1744. autoSlide = ( el.duration * 1000 / el.playbackRate ) + 1000;
  1745. }
  1746. }
  1747. } );
  1748. }
  1749. }
  1750. // Cue the next auto-slide if:
  1751. // - There is an autoSlide value
  1752. // - Auto-sliding isn't paused by the user
  1753. // - The presentation isn't paused
  1754. // - The overview isn't active
  1755. // - The presentation isn't over
  1756. if( autoSlide && !autoSlidePaused && !isPaused() && !overview.isActive() && ( !isLastSlide() || fragments.availableRoutes().next || config.loop === true ) ) {
  1757. autoSlideTimeout = setTimeout( () => {
  1758. if( typeof config.autoSlideMethod === 'function' ) {
  1759. config.autoSlideMethod()
  1760. }
  1761. else {
  1762. navigateNext();
  1763. }
  1764. cueAutoSlide();
  1765. }, autoSlide );
  1766. autoSlideStartTime = Date.now();
  1767. }
  1768. if( autoSlidePlayer ) {
  1769. autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
  1770. }
  1771. }
  1772. }
  1773. /**
  1774. * Cancels any ongoing request to auto-slide.
  1775. */
  1776. function cancelAutoSlide() {
  1777. clearTimeout( autoSlideTimeout );
  1778. autoSlideTimeout = -1;
  1779. }
  1780. function pauseAutoSlide() {
  1781. if( autoSlide && !autoSlidePaused ) {
  1782. autoSlidePaused = true;
  1783. dispatchEvent({ type: 'autoslidepaused' });
  1784. clearTimeout( autoSlideTimeout );
  1785. if( autoSlidePlayer ) {
  1786. autoSlidePlayer.setPlaying( false );
  1787. }
  1788. }
  1789. }
  1790. function resumeAutoSlide() {
  1791. if( autoSlide && autoSlidePaused ) {
  1792. autoSlidePaused = false;
  1793. dispatchEvent({ type: 'autoslideresumed' });
  1794. cueAutoSlide();
  1795. }
  1796. }
  1797. function navigateLeft({skipFragments=false}={}) {
  1798. navigationHistory.hasNavigatedHorizontally = true;
  1799. // Reverse for RTL
  1800. if( config.rtl ) {
  1801. if( ( overview.isActive() || skipFragments || fragments.next() === false ) && availableRoutes().left ) {
  1802. slide( indexh + 1, config.navigationMode === 'grid' ? indexv : undefined );
  1803. }
  1804. }
  1805. // Normal navigation
  1806. else if( ( overview.isActive() || skipFragments || fragments.prev() === false ) && availableRoutes().left ) {
  1807. slide( indexh - 1, config.navigationMode === 'grid' ? indexv : undefined );
  1808. }
  1809. }
  1810. function navigateRight({skipFragments=false}={}) {
  1811. navigationHistory.hasNavigatedHorizontally = true;
  1812. // Reverse for RTL
  1813. if( config.rtl ) {
  1814. if( ( overview.isActive() || skipFragments || fragments.prev() === false ) && availableRoutes().right ) {
  1815. slide( indexh - 1, config.navigationMode === 'grid' ? indexv : undefined );
  1816. }
  1817. }
  1818. // Normal navigation
  1819. else if( ( overview.isActive() || skipFragments || fragments.next() === false ) && availableRoutes().right ) {
  1820. slide( indexh + 1, config.navigationMode === 'grid' ? indexv : undefined );
  1821. }
  1822. }
  1823. function navigateUp({skipFragments=false}={}) {
  1824. // Prioritize hiding fragments
  1825. if( ( overview.isActive() || skipFragments || fragments.prev() === false ) && availableRoutes().up ) {
  1826. slide( indexh, indexv - 1 );
  1827. }
  1828. }
  1829. function navigateDown({skipFragments=false}={}) {
  1830. navigationHistory.hasNavigatedVertically = true;
  1831. // Prioritize revealing fragments
  1832. if( ( overview.isActive() || skipFragments || fragments.next() === false ) && availableRoutes().down ) {
  1833. slide( indexh, indexv + 1 );
  1834. }
  1835. }
  1836. /**
  1837. * Navigates backwards, prioritized in the following order:
  1838. * 1) Previous fragment
  1839. * 2) Previous vertical slide
  1840. * 3) Previous horizontal slide
  1841. */
  1842. function navigatePrev({skipFragments=false}={}) {
  1843. // Prioritize revealing fragments
  1844. if( skipFragments || fragments.prev() === false ) {
  1845. if( availableRoutes().up ) {
  1846. navigateUp({skipFragments});
  1847. }
  1848. else {
  1849. // Fetch the previous horizontal slide, if there is one
  1850. let previousSlide;
  1851. if( config.rtl ) {
  1852. previousSlide = Util.queryAll( dom.wrapper, HORIZONTAL_SLIDES_SELECTOR + '.future' ).pop();
  1853. }
  1854. else {
  1855. previousSlide = Util.queryAll( dom.wrapper, HORIZONTAL_SLIDES_SELECTOR + '.past' ).pop();
  1856. }
  1857. // When going backwards and arriving on a stack we start
  1858. // at the bottom of the stack
  1859. if( previousSlide && previousSlide.classList.contains( 'stack' ) ) {
  1860. let v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
  1861. let h = indexh - 1;
  1862. slide( h, v );
  1863. }
  1864. else {
  1865. navigateLeft({skipFragments});
  1866. }
  1867. }
  1868. }
  1869. }
  1870. /**
  1871. * The reverse of #navigatePrev().
  1872. */
  1873. function navigateNext({skipFragments=false}={}) {
  1874. navigationHistory.hasNavigatedHorizontally = true;
  1875. navigationHistory.hasNavigatedVertically = true;
  1876. // Prioritize revealing fragments
  1877. if( skipFragments || fragments.next() === false ) {
  1878. let routes = availableRoutes();
  1879. // When looping is enabled `routes.down` is always available
  1880. // so we need a separate check for when we've reached the
  1881. // end of a stack and should move horizontally
  1882. if( routes.down && routes.right && config.loop && isLastVerticalSlide() ) {
  1883. routes.down = false;
  1884. }
  1885. if( routes.down ) {
  1886. navigateDown({skipFragments});
  1887. }
  1888. else if( config.rtl ) {
  1889. navigateLeft({skipFragments});
  1890. }
  1891. else {
  1892. navigateRight({skipFragments});
  1893. }
  1894. }
  1895. }
  1896. // --------------------------------------------------------------------//
  1897. // ----------------------------- EVENTS -------------------------------//
  1898. // --------------------------------------------------------------------//
  1899. /**
  1900. * Called by all event handlers that are based on user
  1901. * input.
  1902. *
  1903. * @param {object} [event]
  1904. */
  1905. function onUserInput( event ) {
  1906. if( config.autoSlideStoppable ) {
  1907. pauseAutoSlide();
  1908. }
  1909. }
  1910. /**
  1911. * Listener for post message events posted to this window.
  1912. */
  1913. function onPostMessage( event ) {
  1914. let data = event.data;
  1915. // Make sure we're dealing with JSON
  1916. if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
  1917. data = JSON.parse( data );
  1918. // Check if the requested method can be found
  1919. if( data.method && typeof Reveal[data.method] === 'function' ) {
  1920. if( POST_MESSAGE_METHOD_BLACKLIST.test( data.method ) === false ) {
  1921. const result = Reveal[data.method].apply( Reveal, data.args );
  1922. // Dispatch a postMessage event with the returned value from
  1923. // our method invocation for getter functions
  1924. dispatchPostMessage( 'callback', { method: data.method, result: result } );
  1925. }
  1926. else {
  1927. console.warn( 'reveal.js: "'+ data.method +'" is is blacklisted from the postMessage API' );
  1928. }
  1929. }
  1930. }
  1931. }
  1932. /**
  1933. * Event listener for transition end on the current slide.
  1934. *
  1935. * @param {object} [event]
  1936. */
  1937. function onTransitionEnd( event ) {
  1938. if( transition === 'running' && /section/gi.test( event.target.nodeName ) ) {
  1939. transition = 'idle';
  1940. dispatchEvent({
  1941. type: 'slidetransitionend',
  1942. data: { indexh, indexv, previousSlide, currentSlide }
  1943. });
  1944. }
  1945. }
  1946. /**
  1947. * A global listener for all click events inside of the
  1948. * .slides container.
  1949. *
  1950. * @param {object} [event]
  1951. */
  1952. function onSlidesClicked( event ) {
  1953. const anchor = Util.closest( event.target, 'a[href^="#"]' );
  1954. // If a hash link is clicked, we find the target slide
  1955. // and navigate to it. We previously relied on 'hashchange'
  1956. // for links like these but that prevented media with
  1957. // audio tracks from playing in mobile browsers since it
  1958. // wasn't considered a direct interaction with the document.
  1959. if( anchor ) {
  1960. const hash = anchor.getAttribute( 'href' );
  1961. const indices = location.getIndicesFromHash( hash );
  1962. if( indices ) {
  1963. Reveal.slide( indices.h, indices.v, indices.f );
  1964. event.preventDefault();
  1965. }
  1966. }
  1967. }
  1968. /**
  1969. * Handler for the window level 'resize' event.
  1970. *
  1971. * @param {object} [event]
  1972. */
  1973. function onWindowResize( event ) {
  1974. layout();
  1975. }
  1976. /**
  1977. * Handle for the window level 'visibilitychange' event.
  1978. *
  1979. * @param {object} [event]
  1980. */
  1981. function onPageVisibilityChange( event ) {
  1982. // If, after clicking a link or similar and we're coming back,
  1983. // focus the document.body to ensure we can use keyboard shortcuts
  1984. if( document.hidden === false && document.activeElement !== document.body ) {
  1985. // Not all elements support .blur() - SVGs among them.
  1986. if( typeof document.activeElement.blur === 'function' ) {
  1987. document.activeElement.blur();
  1988. }
  1989. document.body.focus();
  1990. }
  1991. }
  1992. /**
  1993. * Handler for the document level 'fullscreenchange' event.
  1994. *
  1995. * @param {object} [event]
  1996. */
  1997. function onFullscreenChange( event ) {
  1998. let element = document.fullscreenElement || document.webkitFullscreenElement;
  1999. if( element === dom.wrapper ) {
  2000. event.stopImmediatePropagation();
  2001. // Timeout to avoid layout shift in Safari
  2002. setTimeout( () => {
  2003. Reveal.layout();
  2004. Reveal.focus.focus(); // focus.focus :'(
  2005. }, 1 );
  2006. }
  2007. }
  2008. /**
  2009. * Handles clicks on links that are set to preview in the
  2010. * iframe overlay.
  2011. *
  2012. * @param {object} event
  2013. */
  2014. function onPreviewLinkClicked( event ) {
  2015. if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) {
  2016. let url = event.currentTarget.getAttribute( 'href' );
  2017. if( url ) {
  2018. showPreview( url );
  2019. event.preventDefault();
  2020. }
  2021. }
  2022. }
  2023. /**
  2024. * Handles click on the auto-sliding controls element.
  2025. *
  2026. * @param {object} [event]
  2027. */
  2028. function onAutoSlidePlayerClick( event ) {
  2029. // Replay
  2030. if( isLastSlide() && config.loop === false ) {
  2031. slide( 0, 0 );
  2032. resumeAutoSlide();
  2033. }
  2034. // Resume
  2035. else if( autoSlidePaused ) {
  2036. resumeAutoSlide();
  2037. }
  2038. // Pause
  2039. else {
  2040. pauseAutoSlide();
  2041. }
  2042. }
  2043. // --------------------------------------------------------------------//
  2044. // ------------------------------- API --------------------------------//
  2045. // --------------------------------------------------------------------//
  2046. // The public reveal.js API
  2047. const API = {
  2048. VERSION,
  2049. initialize,
  2050. configure,
  2051. destroy,
  2052. sync,
  2053. syncSlide,
  2054. syncFragments: fragments.sync.bind( fragments ),
  2055. // Navigation methods
  2056. slide,
  2057. left: navigateLeft,
  2058. right: navigateRight,
  2059. up: navigateUp,
  2060. down: navigateDown,
  2061. prev: navigatePrev,
  2062. next: navigateNext,
  2063. // Navigation aliases
  2064. navigateLeft, navigateRight, navigateUp, navigateDown, navigatePrev, navigateNext,
  2065. // Fragment methods
  2066. navigateFragment: fragments.goto.bind( fragments ),
  2067. prevFragment: fragments.prev.bind( fragments ),
  2068. nextFragment: fragments.next.bind( fragments ),
  2069. // Event binding
  2070. on,
  2071. off,
  2072. // Legacy event binding methods left in for backwards compatibility
  2073. addEventListener: on,
  2074. removeEventListener: off,
  2075. // Forces an update in slide layout
  2076. layout,
  2077. // Randomizes the order of slides
  2078. shuffle,
  2079. // Returns an object with the available routes as booleans (left/right/top/bottom)
  2080. availableRoutes,
  2081. // Returns an object with the available fragments as booleans (prev/next)
  2082. availableFragments: fragments.availableRoutes.bind( fragments ),
  2083. // Toggles a help overlay with keyboard shortcuts
  2084. toggleHelp,
  2085. // Toggles the overview mode on/off
  2086. toggleOverview: overview.toggle.bind( overview ),
  2087. // Toggles the "black screen" mode on/off
  2088. togglePause,
  2089. // Toggles the auto slide mode on/off
  2090. toggleAutoSlide,
  2091. // Toggles visibility of the jump-to-slide UI
  2092. toggleJumpToSlide,
  2093. // Slide navigation checks
  2094. isFirstSlide,
  2095. isLastSlide,
  2096. isLastVerticalSlide,
  2097. isVerticalSlide,
  2098. // State checks
  2099. isPaused,
  2100. isAutoSliding,
  2101. isSpeakerNotes: notes.isSpeakerNotesWindow.bind( notes ),
  2102. isOverview: overview.isActive.bind( overview ),
  2103. isFocused: focus.isFocused.bind( focus ),
  2104. isPrintingPDF: print.isPrintingPDF.bind( print ),
  2105. // Checks if reveal.js has been loaded and is ready for use
  2106. isReady: () => ready,
  2107. // Slide preloading
  2108. loadSlide: slideContent.load.bind( slideContent ),
  2109. unloadSlide: slideContent.unload.bind( slideContent ),
  2110. // Preview management
  2111. showPreview,
  2112. hidePreview: closeOverlay,
  2113. // Adds or removes all internal event listeners
  2114. addEventListeners,
  2115. removeEventListeners,
  2116. dispatchEvent,
  2117. // Facility for persisting and restoring the presentation state
  2118. getState,
  2119. setState,
  2120. // Presentation progress on range of 0-1
  2121. getProgress,
  2122. // Returns the indices of the current, or specified, slide
  2123. getIndices,
  2124. // Returns an Array of key:value maps of the attributes of each
  2125. // slide in the deck
  2126. getSlidesAttributes,
  2127. // Returns the number of slides that we have passed
  2128. getSlidePastCount,
  2129. // Returns the total number of slides
  2130. getTotalSlides,
  2131. // Returns the slide element at the specified index
  2132. getSlide,
  2133. // Returns the previous slide element, may be null
  2134. getPreviousSlide: () => previousSlide,
  2135. // Returns the current slide element
  2136. getCurrentSlide: () => currentSlide,
  2137. // Returns the slide background element at the specified index
  2138. getSlideBackground,
  2139. // Returns the speaker notes string for a slide, or null
  2140. getSlideNotes: notes.getSlideNotes.bind( notes ),
  2141. // Returns an Array of all slides
  2142. getSlides,
  2143. // Returns an array with all horizontal/vertical slides in the deck
  2144. getHorizontalSlides,
  2145. getVerticalSlides,
  2146. // Checks if the presentation contains two or more horizontal
  2147. // and vertical slides
  2148. hasHorizontalSlides,
  2149. hasVerticalSlides,
  2150. // Checks if the deck has navigated on either axis at least once
  2151. hasNavigatedHorizontally: () => navigationHistory.hasNavigatedHorizontally,
  2152. hasNavigatedVertically: () => navigationHistory.hasNavigatedVertically,
  2153. // Adds/removes a custom key binding
  2154. addKeyBinding: keyboard.addKeyBinding.bind( keyboard ),
  2155. removeKeyBinding: keyboard.removeKeyBinding.bind( keyboard ),
  2156. // Programmatically triggers a keyboard event
  2157. triggerKey: keyboard.triggerKey.bind( keyboard ),
  2158. // Registers a new shortcut to include in the help overlay
  2159. registerKeyboardShortcut: keyboard.registerKeyboardShortcut.bind( keyboard ),
  2160. getComputedSlideSize,
  2161. // Returns the current scale of the presentation content
  2162. getScale: () => scale,
  2163. // Returns the current configuration object
  2164. getConfig: () => config,
  2165. // Helper method, retrieves query string as a key:value map
  2166. getQueryHash: Util.getQueryHash,
  2167. // Returns the path to the current slide as represented in the URL
  2168. getSlidePath: location.getHash.bind( location ),
  2169. // Returns reveal.js DOM elements
  2170. getRevealElement: () => revealElement,
  2171. getSlidesElement: () => dom.slides,
  2172. getViewportElement: () => dom.viewport,
  2173. getBackgroundsElement: () => backgrounds.element,
  2174. // API for registering and retrieving plugins
  2175. registerPlugin: plugins.registerPlugin.bind( plugins ),
  2176. hasPlugin: plugins.hasPlugin.bind( plugins ),
  2177. getPlugin: plugins.getPlugin.bind( plugins ),
  2178. getPlugins: plugins.getRegisteredPlugins.bind( plugins )
  2179. };
  2180. // Our internal API which controllers have access to
  2181. Util.extend( Reveal, {
  2182. ...API,
  2183. // Methods for announcing content to screen readers
  2184. announceStatus,
  2185. getStatusText,
  2186. // Controllers
  2187. print,
  2188. focus,
  2189. progress,
  2190. controls,
  2191. location,
  2192. overview,
  2193. fragments,
  2194. slideContent,
  2195. slideNumber,
  2196. onUserInput,
  2197. closeOverlay,
  2198. updateSlidesVisibility,
  2199. layoutSlideContents,
  2200. transformSlides,
  2201. cueAutoSlide,
  2202. cancelAutoSlide
  2203. } );
  2204. return API;
  2205. };