Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

reveal.js 74KB

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