reveal.js 66 KB

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