reveal.js 73 KB

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