reveal.js 66 KB

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