reveal.js 71 KB

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