reveal.js 67 KB

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