reveal.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  1. /*!
  2. * reveal.js
  3. * http://lab.hakim.se/reveal-js
  4. * MIT licensed
  5. *
  6. * Copyright (C) 2013 Hakim El Hattab, http://hakim.se
  7. */
  8. var Reveal = (function(){
  9. 'use strict';
  10. var SLIDES_SELECTOR = '.reveal .slides section',
  11. HORIZONTAL_SLIDES_SELECTOR = '.reveal .slides>section',
  12. VERTICAL_SLIDES_SELECTOR = '.reveal .slides>section.present>section',
  13. HOME_SLIDE_SELECTOR = '.reveal .slides>section:first-child',
  14. // Configurations defaults, can be overridden at initialization time
  15. config = {
  16. // The "normal" size of the presentation, aspect ratio will be preserved
  17. // when the presentation is scaled to fit different resolutions
  18. width: 960,
  19. height: 700,
  20. // Factor of the display size that should remain empty around the content
  21. margin: 0.1,
  22. // Bounds for smallest/largest possible scale to apply to content
  23. minScale: 0.2,
  24. maxScale: 1.0,
  25. // Display controls in the bottom right corner
  26. controls: true,
  27. // Display a presentation progress bar
  28. progress: true,
  29. // Push each slide change to the browser history
  30. history: false,
  31. // Enable keyboard shortcuts for navigation
  32. keyboard: true,
  33. // Enable the slide overview mode
  34. overview: true,
  35. // Vertical centring of slides
  36. center: true,
  37. // Enables touch navigation on devices with touch input
  38. touch: true,
  39. // Loop the presentation
  40. loop: false,
  41. // Change the presentation direction to be RTL
  42. rtl: false,
  43. // Turns fragments on and off globally
  44. fragments: true,
  45. // Number of milliseconds between automatically proceeding to the
  46. // next slide, disabled when set to 0, this value can be overwritten
  47. // by using a data-autoslide attribute on your slides
  48. autoSlide: 0,
  49. // Enable slide navigation via mouse wheel
  50. mouseWheel: false,
  51. // Apply a 3D roll to links on hover
  52. rollingLinks: true,
  53. // Opens links in an iframe preview overlay
  54. previewLinks: false,
  55. // Theme (see /css/theme)
  56. theme: null,
  57. // Transition style
  58. transition: 'default', // default/cube/page/concave/zoom/linear/fade/none
  59. // Transition speed
  60. transitionSpeed: 'default', // default/fast/slow
  61. // Transition style for full page slide backgrounds
  62. backgroundTransition: 'default', // default/linear
  63. // Script dependencies to load
  64. dependencies: []
  65. },
  66. // The current auto-slide duration
  67. autoSlide = 0,
  68. // The horizontal and vertical index of the currently active slide
  69. indexh = 0,
  70. indexv = 0,
  71. // The previous and current slide HTML elements
  72. previousSlide,
  73. currentSlide,
  74. // Slides may hold a data-state attribute which we pick up and apply
  75. // as a class to the body. This list contains the combined state of
  76. // all current slides.
  77. state = [],
  78. // The current scale of the presentation (see width/height config)
  79. scale = 1,
  80. // Cached references to DOM elements
  81. dom = {},
  82. // Detect support for CSS 3D transforms
  83. supports3DTransforms = 'WebkitPerspective' in document.body.style ||
  84. 'MozPerspective' in document.body.style ||
  85. 'msPerspective' in document.body.style ||
  86. 'OPerspective' in document.body.style ||
  87. 'perspective' in document.body.style,
  88. // Detect support for CSS 2D transforms
  89. supports2DTransforms = 'WebkitTransform' in document.body.style ||
  90. 'MozTransform' in document.body.style ||
  91. 'msTransform' in document.body.style ||
  92. 'OTransform' in document.body.style ||
  93. 'transform' in document.body.style,
  94. // Throttles mouse wheel navigation
  95. lastMouseWheelStep = 0,
  96. // An interval used to automatically move on to the next slide
  97. autoSlideTimeout = 0,
  98. // Delays updates to the URL due to a Chrome thumbnailer bug
  99. writeURLTimeout = 0,
  100. // A delay used to activate the overview mode
  101. activateOverviewTimeout = 0,
  102. // A delay used to deactivate the overview mode
  103. deactivateOverviewTimeout = 0,
  104. // Flags if the interaction event listeners are bound
  105. eventsAreBound = false,
  106. // Holds information about the currently ongoing touch input
  107. touch = {
  108. startX: 0,
  109. startY: 0,
  110. startSpan: 0,
  111. startCount: 0,
  112. handled: false,
  113. threshold: 80
  114. };
  115. /**
  116. * Starts up the presentation if the client is capable.
  117. */
  118. function initialize( options ) {
  119. if( !supports2DTransforms && !supports3DTransforms ) {
  120. document.body.setAttribute( 'class', 'no-transforms' );
  121. // If the browser doesn't support core features we won't be
  122. // using JavaScript to control the presentation
  123. return;
  124. }
  125. // Force a layout when the whole page, incl fonts, has loaded
  126. window.addEventListener( 'load', layout, false );
  127. // Copy options over to our config object
  128. extend( config, options );
  129. // Hide the address bar in mobile browsers
  130. hideAddressBar();
  131. // Loads the dependencies and continues to #start() once done
  132. load();
  133. }
  134. /**
  135. * Finds and stores references to DOM elements which are
  136. * required by the presentation. If a required element is
  137. * not found, it is created.
  138. */
  139. function setupDOM() {
  140. // Cache references to key DOM elements
  141. dom.theme = document.querySelector( '#theme' );
  142. dom.wrapper = document.querySelector( '.reveal' );
  143. dom.slides = document.querySelector( '.reveal .slides' );
  144. // Background element
  145. if( !document.querySelector( '.reveal .backgrounds' ) ) {
  146. dom.background = document.createElement( 'div' );
  147. dom.background.classList.add( 'backgrounds' );
  148. dom.wrapper.appendChild( dom.background );
  149. }
  150. // Progress bar
  151. if( !dom.wrapper.querySelector( '.progress' ) ) {
  152. var progressElement = document.createElement( 'div' );
  153. progressElement.classList.add( 'progress' );
  154. progressElement.innerHTML = '<span></span>';
  155. dom.wrapper.appendChild( progressElement );
  156. }
  157. // Arrow controls
  158. if( !dom.wrapper.querySelector( '.controls' ) ) {
  159. var controlsElement = document.createElement( 'aside' );
  160. controlsElement.classList.add( 'controls' );
  161. controlsElement.innerHTML = '<div class="navigate-left"></div>' +
  162. '<div class="navigate-right"></div>' +
  163. '<div class="navigate-up"></div>' +
  164. '<div class="navigate-down"></div>';
  165. dom.wrapper.appendChild( controlsElement );
  166. }
  167. // State background element [DEPRECATED]
  168. if( !dom.wrapper.querySelector( '.state-background' ) ) {
  169. var stateBackgroundElement = document.createElement( 'div' );
  170. stateBackgroundElement.classList.add( 'state-background' );
  171. dom.wrapper.appendChild( stateBackgroundElement );
  172. }
  173. // Overlay graphic which is displayed during the paused mode
  174. if( !dom.wrapper.querySelector( '.pause-overlay' ) ) {
  175. var pausedElement = document.createElement( 'div' );
  176. pausedElement.classList.add( 'pause-overlay' );
  177. dom.wrapper.appendChild( pausedElement );
  178. }
  179. // Cache references to elements
  180. dom.progress = document.querySelector( '.reveal .progress' );
  181. dom.progressbar = document.querySelector( '.reveal .progress span' );
  182. if ( config.controls ) {
  183. dom.controls = document.querySelector( '.reveal .controls' );
  184. // There can be multiple instances of controls throughout the page
  185. dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
  186. dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
  187. dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
  188. dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
  189. dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
  190. dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
  191. }
  192. }
  193. /**
  194. * Creates the slide background elements and appends them
  195. * to the background container. One element is created per
  196. * slide no matter if the given slide has visible background.
  197. */
  198. function createBackgrounds() {
  199. if( isPrintingPDF() ) {
  200. document.body.classList.add( 'print-pdf' );
  201. }
  202. // Clear prior backgrounds
  203. dom.background.innerHTML = '';
  204. dom.background.classList.add( 'no-transition' );
  205. // Helper method for creating a background element for the
  206. // given slide
  207. function _createBackground( slide, container ) {
  208. var data = {
  209. background: slide.getAttribute( 'data-background' ),
  210. backgroundSize: slide.getAttribute( 'data-background-size' ),
  211. backgroundColor: slide.getAttribute( 'data-background-color' ),
  212. backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
  213. backgroundPosition: slide.getAttribute( 'data-background-position' )
  214. };
  215. var element = document.createElement( 'div' );
  216. element.className = 'slide-background';
  217. if( data.background ) {
  218. // Auto-wrap image urls in url(...)
  219. if( /\.(png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) {
  220. element.style.backgroundImage = 'url('+ data.background +')';
  221. }
  222. else {
  223. element.style.background = data.background;
  224. }
  225. }
  226. // Additional and optional background properties
  227. if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
  228. if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
  229. if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
  230. if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
  231. container.appendChild( element );
  232. return element;
  233. }
  234. // Iterate over all horizontal slides
  235. toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
  236. var backgroundStack;
  237. if( isPrintingPDF() ) {
  238. backgroundStack = _createBackground( slideh, slideh );
  239. }
  240. else {
  241. backgroundStack = _createBackground( slideh, dom.background );
  242. }
  243. // Iterate over all vertical slides
  244. toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
  245. if( isPrintingPDF() ) {
  246. _createBackground( slidev, slidev );
  247. }
  248. else {
  249. _createBackground( slidev, backgroundStack );
  250. }
  251. } );
  252. } );
  253. }
  254. /**
  255. * Hides the address bar if we're on a mobile device.
  256. */
  257. function hideAddressBar() {
  258. if( /iphone|ipod|android/gi.test( navigator.userAgent ) && !/crios/gi.test( navigator.userAgent ) ) {
  259. // Events that should trigger the address bar to hide
  260. window.addEventListener( 'load', removeAddressBar, false );
  261. window.addEventListener( 'orientationchange', removeAddressBar, false );
  262. }
  263. }
  264. /**
  265. * Loads the dependencies of reveal.js. Dependencies are
  266. * defined via the configuration option 'dependencies'
  267. * and will be loaded prior to starting/binding reveal.js.
  268. * Some dependencies may have an 'async' flag, if so they
  269. * will load after reveal.js has been started up.
  270. */
  271. function load() {
  272. var scripts = [],
  273. scriptsAsync = [];
  274. for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
  275. var s = config.dependencies[i];
  276. // Load if there's no condition or the condition is truthy
  277. if( !s.condition || s.condition() ) {
  278. if( s.async ) {
  279. scriptsAsync.push( s.src );
  280. }
  281. else {
  282. scripts.push( s.src );
  283. }
  284. // Extension may contain callback functions
  285. if( typeof s.callback === 'function' ) {
  286. head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], s.callback );
  287. }
  288. }
  289. }
  290. // Called once synchronous scripts finish loading
  291. function proceed() {
  292. if( scriptsAsync.length ) {
  293. // Load asynchronous scripts
  294. head.js.apply( null, scriptsAsync );
  295. }
  296. start();
  297. }
  298. if( scripts.length ) {
  299. head.ready( proceed );
  300. // Load synchronous scripts
  301. head.js.apply( null, scripts );
  302. }
  303. else {
  304. proceed();
  305. }
  306. }
  307. /**
  308. * Starts up reveal.js by binding input events and navigating
  309. * to the current URL deeplink if there is one.
  310. */
  311. function start() {
  312. // Make sure we've got all the DOM elements we need
  313. setupDOM();
  314. // Updates the presentation to match the current configuration values
  315. configure();
  316. // Read the initial hash
  317. readURL();
  318. // Notify listeners that the presentation is ready but use a 1ms
  319. // timeout to ensure it's not fired synchronously after #initialize()
  320. setTimeout( function() {
  321. dispatchEvent( 'ready', {
  322. 'indexh': indexh,
  323. 'indexv': indexv,
  324. 'currentSlide': currentSlide
  325. } );
  326. }, 1 );
  327. }
  328. /**
  329. * Applies the configuration settings from the config
  330. * object. May be called multiple times.
  331. */
  332. function configure( options ) {
  333. dom.wrapper.classList.remove( config.transition );
  334. // New config options may be passed when this method
  335. // is invoked through the API after initialization
  336. if( typeof options === 'object' ) extend( config, options );
  337. // Force linear transition based on browser capabilities
  338. if( supports3DTransforms === false ) config.transition = 'linear';
  339. dom.wrapper.classList.add( config.transition );
  340. dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
  341. dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
  342. if( dom.controls ) {
  343. dom.controls.style.display = ( config.controls && dom.controls ) ? 'block' : 'none';
  344. }
  345. if( dom.progress ) {
  346. dom.progress.style.display = ( config.progress && dom.progress ) ? 'block' : 'none';
  347. }
  348. if( config.rtl ) {
  349. dom.wrapper.classList.add( 'rtl' );
  350. }
  351. else {
  352. dom.wrapper.classList.remove( 'rtl' );
  353. }
  354. if( config.center ) {
  355. dom.wrapper.classList.add( 'center' );
  356. }
  357. else {
  358. dom.wrapper.classList.remove( 'center' );
  359. }
  360. if( config.mouseWheel ) {
  361. document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
  362. document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
  363. }
  364. else {
  365. document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
  366. document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
  367. }
  368. // Rolling 3D links
  369. if( config.rollingLinks ) {
  370. enableRollingLinks();
  371. }
  372. else {
  373. disableRollingLinks();
  374. }
  375. // Iframe link previews
  376. if( config.previewLinks ) {
  377. enablePreviewLinks();
  378. }
  379. else {
  380. disablePreviewLinks();
  381. enablePreviewLinks( '[data-preview-link]' );
  382. }
  383. // Load the theme in the config, if it's not already loaded
  384. if( config.theme && dom.theme ) {
  385. var themeURL = dom.theme.getAttribute( 'href' );
  386. var themeFinder = /[^\/]*?(?=\.css)/;
  387. var themeName = themeURL.match(themeFinder)[0];
  388. if( config.theme !== themeName ) {
  389. themeURL = themeURL.replace(themeFinder, config.theme);
  390. dom.theme.setAttribute( 'href', themeURL );
  391. }
  392. }
  393. sync();
  394. }
  395. /**
  396. * Binds all event listeners.
  397. */
  398. function addEventListeners() {
  399. eventsAreBound = true;
  400. window.addEventListener( 'hashchange', onWindowHashChange, false );
  401. window.addEventListener( 'resize', onWindowResize, false );
  402. if( config.touch ) {
  403. dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
  404. dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
  405. dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
  406. // Support pointer-style touch interaction as well
  407. if( window.navigator.msPointerEnabled ) {
  408. dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
  409. dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
  410. dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
  411. }
  412. }
  413. if( config.keyboard ) {
  414. document.addEventListener( 'keydown', onDocumentKeyDown, false );
  415. }
  416. if ( config.progress && dom.progress ) {
  417. dom.progress.addEventListener( 'click', onProgressClicked, false );
  418. }
  419. if ( config.controls && dom.controls ) {
  420. [ 'touchstart', 'click' ].forEach( function( eventName ) {
  421. dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
  422. dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
  423. dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
  424. dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
  425. dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
  426. dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
  427. } );
  428. }
  429. }
  430. /**
  431. * Unbinds all event listeners.
  432. */
  433. function removeEventListeners() {
  434. eventsAreBound = false;
  435. document.removeEventListener( 'keydown', onDocumentKeyDown, false );
  436. window.removeEventListener( 'hashchange', onWindowHashChange, false );
  437. window.removeEventListener( 'resize', onWindowResize, false );
  438. dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
  439. dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
  440. dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
  441. if( window.navigator.msPointerEnabled ) {
  442. dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
  443. dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
  444. dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
  445. }
  446. if ( config.progress && dom.progress ) {
  447. dom.progress.removeEventListener( 'click', onProgressClicked, false );
  448. }
  449. if ( config.controls && dom.controls ) {
  450. [ 'touchstart', 'click' ].forEach( function( eventName ) {
  451. dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
  452. dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
  453. dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
  454. dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
  455. dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
  456. dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
  457. } );
  458. }
  459. }
  460. /**
  461. * Extend object a with the properties of object b.
  462. * If there's a conflict, object b takes precedence.
  463. */
  464. function extend( a, b ) {
  465. for( var i in b ) {
  466. a[ i ] = b[ i ];
  467. }
  468. }
  469. /**
  470. * Converts the target object to an array.
  471. */
  472. function toArray( o ) {
  473. return Array.prototype.slice.call( o );
  474. }
  475. /**
  476. * Measures the distance in pixels between point a
  477. * and point b.
  478. *
  479. * @param {Object} a point with x/y properties
  480. * @param {Object} b point with x/y properties
  481. */
  482. function distanceBetween( a, b ) {
  483. var dx = a.x - b.x,
  484. dy = a.y - b.y;
  485. return Math.sqrt( dx*dx + dy*dy );
  486. }
  487. /**
  488. * Retrieves the height of the given element by looking
  489. * at the position and height of its immediate children.
  490. */
  491. function getAbsoluteHeight( element ) {
  492. var height = 0;
  493. if( element ) {
  494. var absoluteChildren = 0;
  495. toArray( element.childNodes ).forEach( function( child ) {
  496. if( typeof child.offsetTop === 'number' && child.style ) {
  497. // Count # of abs children
  498. if( child.style.position === 'absolute' ) {
  499. absoluteChildren += 1;
  500. }
  501. height = Math.max( height, child.offsetTop + child.offsetHeight );
  502. }
  503. } );
  504. // If there are no absolute children, use offsetHeight
  505. if( absoluteChildren === 0 ) {
  506. height = element.offsetHeight;
  507. }
  508. }
  509. return height;
  510. }
  511. /**
  512. * Checks if this instance is being used to print a PDF.
  513. */
  514. function isPrintingPDF() {
  515. return ( /print-pdf/gi ).test( window.location.search );
  516. }
  517. /**
  518. * Causes the address bar to hide on mobile devices,
  519. * more vertical space ftw.
  520. */
  521. function removeAddressBar() {
  522. if( window.orientation === 0 ) {
  523. document.documentElement.style.overflow = 'scroll';
  524. document.body.style.height = '120%';
  525. }
  526. else {
  527. document.documentElement.style.overflow = '';
  528. document.body.style.height = '100%';
  529. }
  530. setTimeout( function() {
  531. window.scrollTo( 0, 1 );
  532. }, 10 );
  533. }
  534. /**
  535. * Dispatches an event of the specified type from the
  536. * reveal DOM element.
  537. */
  538. function dispatchEvent( type, properties ) {
  539. var event = document.createEvent( "HTMLEvents", 1, 2 );
  540. event.initEvent( type, true, true );
  541. extend( event, properties );
  542. dom.wrapper.dispatchEvent( event );
  543. }
  544. /**
  545. * Wrap all links in 3D goodness.
  546. */
  547. function enableRollingLinks() {
  548. if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
  549. var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
  550. for( var i = 0, len = anchors.length; i < len; i++ ) {
  551. var anchor = anchors[i];
  552. if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
  553. var span = document.createElement('span');
  554. span.setAttribute('data-title', anchor.text);
  555. span.innerHTML = anchor.innerHTML;
  556. anchor.classList.add( 'roll' );
  557. anchor.innerHTML = '';
  558. anchor.appendChild(span);
  559. }
  560. }
  561. }
  562. }
  563. /**
  564. * Unwrap all 3D links.
  565. */
  566. function disableRollingLinks() {
  567. var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
  568. for( var i = 0, len = anchors.length; i < len; i++ ) {
  569. var anchor = anchors[i];
  570. var span = anchor.querySelector( 'span' );
  571. if( span ) {
  572. anchor.classList.remove( 'roll' );
  573. anchor.innerHTML = span.innerHTML;
  574. }
  575. }
  576. }
  577. /**
  578. * Bind preview frame links.
  579. */
  580. function enablePreviewLinks( selector ) {
  581. var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
  582. anchors.forEach( function( element ) {
  583. if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
  584. element.addEventListener( 'click', onPreviewLinkClicked, false );
  585. }
  586. } );
  587. }
  588. /**
  589. * Unbind preview frame links.
  590. */
  591. function disablePreviewLinks() {
  592. var anchors = toArray( document.querySelectorAll( 'a' ) );
  593. anchors.forEach( function( element ) {
  594. if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
  595. element.removeEventListener( 'click', onPreviewLinkClicked, false );
  596. }
  597. } );
  598. }
  599. /**
  600. * Opens a preview window for the target URL.
  601. */
  602. function openPreview( url ) {
  603. closePreview();
  604. dom.preview = document.createElement( 'div' );
  605. dom.preview.classList.add( 'preview-link-overlay' );
  606. dom.wrapper.appendChild( dom.preview );
  607. dom.preview.innerHTML = [
  608. '<header>',
  609. '<a class="close" href="#"><span class="icon"></span></a>',
  610. '<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
  611. '</header>',
  612. '<div class="spinner"></div>',
  613. '<div class="viewport">',
  614. '<iframe src="'+ url +'"></iframe>',
  615. '</div>'
  616. ].join('');
  617. dom.preview.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
  618. dom.preview.classList.add( 'loaded' );
  619. }, false );
  620. dom.preview.querySelector( '.close' ).addEventListener( 'click', function( event ) {
  621. closePreview();
  622. event.preventDefault();
  623. }, false );
  624. dom.preview.querySelector( '.external' ).addEventListener( 'click', function( event ) {
  625. closePreview();
  626. }, false );
  627. setTimeout( function() {
  628. dom.preview.classList.add( 'visible' );
  629. }, 1 );
  630. }
  631. /**
  632. * Closes the iframe preview window.
  633. */
  634. function closePreview() {
  635. if( dom.preview ) {
  636. dom.preview.setAttribute( 'src', '' );
  637. dom.preview.parentNode.removeChild( dom.preview );
  638. dom.preview = null;
  639. }
  640. }
  641. /**
  642. * Return a sorted fragments list, ordered by an increasing
  643. * "data-fragment-index" attribute.
  644. *
  645. * Fragments will be revealed in the order that they are returned by
  646. * this function, so you can use the index attributes to control the
  647. * order of fragment appearance.
  648. *
  649. * To maintain a sensible default fragment order, fragments are presumed
  650. * to be passed in document order. This function adds a "fragment-index"
  651. * attribute to each node if such an attribute is not already present,
  652. * and sets that attribute to an integer value which is the position of
  653. * the fragment within the fragments list.
  654. */
  655. function sortFragments( fragments ) {
  656. var a = toArray( fragments );
  657. a.forEach( function( el, idx ) {
  658. if( !el.hasAttribute( 'data-fragment-index' ) ) {
  659. el.setAttribute( 'data-fragment-index', idx );
  660. }
  661. } );
  662. a.sort( function( l, r ) {
  663. return l.getAttribute( 'data-fragment-index' ) - r.getAttribute( 'data-fragment-index');
  664. } );
  665. return a;
  666. }
  667. /**
  668. * Applies JavaScript-controlled layout rules to the
  669. * presentation.
  670. */
  671. function layout() {
  672. if( dom.wrapper && !isPrintingPDF() ) {
  673. // Available space to scale within
  674. var availableWidth = dom.wrapper.offsetWidth,
  675. availableHeight = dom.wrapper.offsetHeight;
  676. // Reduce available space by margin
  677. availableWidth -= ( availableHeight * config.margin );
  678. availableHeight -= ( availableHeight * config.margin );
  679. // Dimensions of the content
  680. var slideWidth = config.width,
  681. slideHeight = config.height;
  682. // Slide width may be a percentage of available width
  683. if( typeof slideWidth === 'string' && /%$/.test( slideWidth ) ) {
  684. slideWidth = parseInt( slideWidth, 10 ) / 100 * availableWidth;
  685. }
  686. // Slide height may be a percentage of available height
  687. if( typeof slideHeight === 'string' && /%$/.test( slideHeight ) ) {
  688. slideHeight = parseInt( slideHeight, 10 ) / 100 * availableHeight;
  689. }
  690. dom.slides.style.width = slideWidth + 'px';
  691. dom.slides.style.height = slideHeight + 'px';
  692. // Determine scale of content to fit within available space
  693. scale = Math.min( availableWidth / slideWidth, availableHeight / slideHeight );
  694. // Respect max/min scale settings
  695. scale = Math.max( scale, config.minScale );
  696. scale = Math.min( scale, config.maxScale );
  697. // Prefer applying scale via zoom since Chrome blurs scaled content
  698. // with nested transforms
  699. if( typeof dom.slides.style.zoom !== 'undefined' && !navigator.userAgent.match( /(iphone|ipod|ipad|android)/gi ) ) {
  700. dom.slides.style.zoom = scale;
  701. }
  702. // Apply scale transform as a fallback
  703. else {
  704. var transform = 'translate(-50%, -50%) scale('+ scale +') translate(50%, 50%)';
  705. dom.slides.style.WebkitTransform = transform;
  706. dom.slides.style.MozTransform = transform;
  707. dom.slides.style.msTransform = transform;
  708. dom.slides.style.OTransform = transform;
  709. dom.slides.style.transform = transform;
  710. }
  711. // Select all slides, vertical and horizontal
  712. var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
  713. for( var i = 0, len = slides.length; i < len; i++ ) {
  714. var slide = slides[ i ];
  715. // Don't bother updating invisible slides
  716. if( slide.style.display === 'none' ) {
  717. continue;
  718. }
  719. if( config.center ) {
  720. // Vertical stacks are not centred since their section
  721. // children will be
  722. if( slide.classList.contains( 'stack' ) ) {
  723. slide.style.top = 0;
  724. }
  725. else {
  726. slide.style.top = Math.max( - ( getAbsoluteHeight( slide ) / 2 ) - 20, -slideHeight / 2 ) + 'px';
  727. }
  728. }
  729. else {
  730. slide.style.top = '';
  731. }
  732. }
  733. updateProgress();
  734. }
  735. }
  736. /**
  737. * Stores the vertical index of a stack so that the same
  738. * vertical slide can be selected when navigating to and
  739. * from the stack.
  740. *
  741. * @param {HTMLElement} stack The vertical stack element
  742. * @param {int} v Index to memorize
  743. */
  744. function setPreviousVerticalIndex( stack, v ) {
  745. if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
  746. stack.setAttribute( 'data-previous-indexv', v || 0 );
  747. }
  748. }
  749. /**
  750. * Retrieves the vertical index which was stored using
  751. * #setPreviousVerticalIndex() or 0 if no previous index
  752. * exists.
  753. *
  754. * @param {HTMLElement} stack The vertical stack element
  755. */
  756. function getPreviousVerticalIndex( stack ) {
  757. if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
  758. // Prefer manually defined start-indexv
  759. var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
  760. return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
  761. }
  762. return 0;
  763. }
  764. /**
  765. * Displays the overview of slides (quick nav) by
  766. * scaling down and arranging all slide elements.
  767. *
  768. * Experimental feature, might be dropped if perf
  769. * can't be improved.
  770. */
  771. function activateOverview() {
  772. // Only proceed if enabled in config
  773. if( config.overview ) {
  774. // Don't auto-slide while in overview mode
  775. cancelAutoSlide();
  776. var wasActive = dom.wrapper.classList.contains( 'overview' );
  777. dom.wrapper.classList.add( 'overview' );
  778. dom.wrapper.classList.remove( 'exit-overview' );
  779. clearTimeout( activateOverviewTimeout );
  780. clearTimeout( deactivateOverviewTimeout );
  781. // Not the pretties solution, but need to let the overview
  782. // class apply first so that slides are measured accurately
  783. // before we can position them
  784. activateOverviewTimeout = setTimeout( function(){
  785. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
  786. for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
  787. var hslide = horizontalSlides[i],
  788. hoffset = config.rtl ? -105 : 105,
  789. htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * hoffset ) + '%, 0%)';
  790. hslide.setAttribute( 'data-index-h', i );
  791. hslide.style.display = 'block';
  792. hslide.style.WebkitTransform = htransform;
  793. hslide.style.MozTransform = htransform;
  794. hslide.style.msTransform = htransform;
  795. hslide.style.OTransform = htransform;
  796. hslide.style.transform = htransform;
  797. if( hslide.classList.contains( 'stack' ) ) {
  798. var verticalSlides = hslide.querySelectorAll( 'section' );
  799. for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
  800. var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
  801. var vslide = verticalSlides[j],
  802. vtransform = 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)';
  803. vslide.setAttribute( 'data-index-h', i );
  804. vslide.setAttribute( 'data-index-v', j );
  805. vslide.style.display = 'block';
  806. vslide.style.WebkitTransform = vtransform;
  807. vslide.style.MozTransform = vtransform;
  808. vslide.style.msTransform = vtransform;
  809. vslide.style.OTransform = vtransform;
  810. vslide.style.transform = vtransform;
  811. // Navigate to this slide on click
  812. vslide.addEventListener( 'click', onOverviewSlideClicked, true );
  813. }
  814. }
  815. else {
  816. // Navigate to this slide on click
  817. hslide.addEventListener( 'click', onOverviewSlideClicked, true );
  818. }
  819. }
  820. layout();
  821. if( !wasActive ) {
  822. // Notify observers of the overview showing
  823. dispatchEvent( 'overviewshown', {
  824. 'indexh': indexh,
  825. 'indexv': indexv,
  826. 'currentSlide': currentSlide
  827. } );
  828. }
  829. }, 10 );
  830. }
  831. }
  832. /**
  833. * Exits the slide overview and enters the currently
  834. * active slide.
  835. */
  836. function deactivateOverview() {
  837. // Only proceed if enabled in config
  838. if( config.overview ) {
  839. clearTimeout( activateOverviewTimeout );
  840. clearTimeout( deactivateOverviewTimeout );
  841. dom.wrapper.classList.remove( 'overview' );
  842. // Temporarily add a class so that transitions can do different things
  843. // depending on whether they are exiting/entering overview, or just
  844. // moving from slide to slide
  845. dom.wrapper.classList.add( 'exit-overview' );
  846. deactivateOverviewTimeout = setTimeout( function () {
  847. dom.wrapper.classList.remove( 'exit-overview' );
  848. }, 10);
  849. // Select all slides
  850. var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
  851. for( var i = 0, len = slides.length; i < len; i++ ) {
  852. var element = slides[i];
  853. element.style.display = '';
  854. // Resets all transforms to use the external styles
  855. element.style.WebkitTransform = '';
  856. element.style.MozTransform = '';
  857. element.style.msTransform = '';
  858. element.style.OTransform = '';
  859. element.style.transform = '';
  860. element.removeEventListener( 'click', onOverviewSlideClicked, true );
  861. }
  862. slide( indexh, indexv );
  863. cueAutoSlide();
  864. // Notify observers of the overview hiding
  865. dispatchEvent( 'overviewhidden', {
  866. 'indexh': indexh,
  867. 'indexv': indexv,
  868. 'currentSlide': currentSlide
  869. } );
  870. }
  871. }
  872. /**
  873. * Toggles the slide overview mode on and off.
  874. *
  875. * @param {Boolean} override Optional flag which overrides the
  876. * toggle logic and forcibly sets the desired state. True means
  877. * overview is open, false means it's closed.
  878. */
  879. function toggleOverview( override ) {
  880. if( typeof override === 'boolean' ) {
  881. override ? activateOverview() : deactivateOverview();
  882. }
  883. else {
  884. isOverview() ? deactivateOverview() : activateOverview();
  885. }
  886. }
  887. /**
  888. * Checks if the overview is currently active.
  889. *
  890. * @return {Boolean} true if the overview is active,
  891. * false otherwise
  892. */
  893. function isOverview() {
  894. return dom.wrapper.classList.contains( 'overview' );
  895. }
  896. /**
  897. * Checks if the current or specified slide is vertical
  898. * (nested within another slide).
  899. *
  900. * @param {HTMLElement} slide [optional] The slide to check
  901. * orientation of
  902. */
  903. function isVerticalSlide( slide ) {
  904. // Prefer slide argument, otherwise use current slide
  905. slide = slide ? slide : currentSlide;
  906. return slide && !!slide.parentNode.nodeName.match( /section/i );
  907. }
  908. /**
  909. * Handling the fullscreen functionality via the fullscreen API
  910. *
  911. * @see http://fullscreen.spec.whatwg.org/
  912. * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
  913. */
  914. function enterFullscreen() {
  915. var element = document.body;
  916. // Check which implementation is available
  917. var requestMethod = element.requestFullScreen ||
  918. element.webkitRequestFullscreen ||
  919. element.webkitRequestFullScreen ||
  920. element.mozRequestFullScreen ||
  921. element.msRequestFullScreen;
  922. if( requestMethod ) {
  923. requestMethod.apply( element );
  924. }
  925. }
  926. /**
  927. * Enters the paused mode which fades everything on screen to
  928. * black.
  929. */
  930. function pause() {
  931. var wasPaused = dom.wrapper.classList.contains( 'paused' );
  932. cancelAutoSlide();
  933. dom.wrapper.classList.add( 'paused' );
  934. if( wasPaused === false ) {
  935. dispatchEvent( 'paused' );
  936. }
  937. }
  938. /**
  939. * Exits from the paused mode.
  940. */
  941. function resume() {
  942. var wasPaused = dom.wrapper.classList.contains( 'paused' );
  943. dom.wrapper.classList.remove( 'paused' );
  944. cueAutoSlide();
  945. if( wasPaused ) {
  946. dispatchEvent( 'resumed' );
  947. }
  948. }
  949. /**
  950. * Toggles the paused mode on and off.
  951. */
  952. function togglePause() {
  953. if( isPaused() ) {
  954. resume();
  955. }
  956. else {
  957. pause();
  958. }
  959. }
  960. /**
  961. * Checks if we are currently in the paused mode.
  962. */
  963. function isPaused() {
  964. return dom.wrapper.classList.contains( 'paused' );
  965. }
  966. /**
  967. * Steps from the current point in the presentation to the
  968. * slide which matches the specified horizontal and vertical
  969. * indices.
  970. *
  971. * @param {int} h Horizontal index of the target slide
  972. * @param {int} v Vertical index of the target slide
  973. * @param {int} f Optional index of a fragment within the
  974. * target slide to activate
  975. * @param {int} o Optional origin for use in multimaster environments
  976. */
  977. function slide( h, v, f, o ) {
  978. // Remember where we were at before
  979. previousSlide = currentSlide;
  980. // Query all horizontal slides in the deck
  981. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
  982. // If no vertical index is specified and the upcoming slide is a
  983. // stack, resume at its previous vertical index
  984. if( v === undefined ) {
  985. v = getPreviousVerticalIndex( horizontalSlides[ h ] );
  986. }
  987. // If we were on a vertical stack, remember what vertical index
  988. // it was on so we can resume at the same position when returning
  989. if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
  990. setPreviousVerticalIndex( previousSlide.parentNode, indexv );
  991. }
  992. // Remember the state before this slide
  993. var stateBefore = state.concat();
  994. // Reset the state array
  995. state.length = 0;
  996. var indexhBefore = indexh,
  997. indexvBefore = indexv;
  998. // Activate and transition to the new slide
  999. indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
  1000. indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
  1001. layout();
  1002. // Apply the new state
  1003. stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
  1004. // Check if this state existed on the previous slide. If it
  1005. // did, we will avoid adding it repeatedly
  1006. for( var j = 0; j < stateBefore.length; j++ ) {
  1007. if( stateBefore[j] === state[i] ) {
  1008. stateBefore.splice( j, 1 );
  1009. continue stateLoop;
  1010. }
  1011. }
  1012. document.documentElement.classList.add( state[i] );
  1013. // Dispatch custom event matching the state's name
  1014. dispatchEvent( state[i] );
  1015. }
  1016. // Clean up the remains of the previous state
  1017. while( stateBefore.length ) {
  1018. document.documentElement.classList.remove( stateBefore.pop() );
  1019. }
  1020. // If the overview is active, re-activate it to update positions
  1021. if( isOverview() ) {
  1022. activateOverview();
  1023. }
  1024. // Update the URL hash after a delay since updating it mid-transition
  1025. // is likely to cause visual lag
  1026. writeURL( 1500 );
  1027. // Find the current horizontal slide and any possible vertical slides
  1028. // within it
  1029. var currentHorizontalSlide = horizontalSlides[ indexh ],
  1030. currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
  1031. // Store references to the previous and current slides
  1032. currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
  1033. // Show fragment, if specified
  1034. if( typeof f !== 'undefined' ) {
  1035. var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
  1036. toArray( fragments ).forEach( function( fragment, indexf ) {
  1037. if( indexf < f ) {
  1038. fragment.classList.add( 'visible' );
  1039. }
  1040. else {
  1041. fragment.classList.remove( 'visible' );
  1042. }
  1043. } );
  1044. }
  1045. // Dispatch an event if the slide changed
  1046. var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
  1047. if( slideChanged ) {
  1048. dispatchEvent( 'slidechanged', {
  1049. 'indexh': indexh,
  1050. 'indexv': indexv,
  1051. 'previousSlide': previousSlide,
  1052. 'currentSlide': currentSlide,
  1053. 'origin': o
  1054. } );
  1055. }
  1056. else {
  1057. // Ensure that the previous slide is never the same as the current
  1058. previousSlide = null;
  1059. }
  1060. // Solves an edge case where the previous slide maintains the
  1061. // 'present' class when navigating between adjacent vertical
  1062. // stacks
  1063. if( previousSlide ) {
  1064. previousSlide.classList.remove( 'present' );
  1065. // Reset all slides upon navigate to home
  1066. // Issue: #285
  1067. if ( document.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
  1068. // Launch async task
  1069. setTimeout( function () {
  1070. var slides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
  1071. for( i in slides ) {
  1072. if( slides[i] ) {
  1073. // Reset stack
  1074. setPreviousVerticalIndex( slides[i], 0 );
  1075. }
  1076. }
  1077. }, 0 );
  1078. }
  1079. }
  1080. // Handle embedded content
  1081. if( slideChanged ) {
  1082. stopEmbeddedContent( previousSlide );
  1083. startEmbeddedContent( currentSlide );
  1084. }
  1085. updateControls();
  1086. updateProgress();
  1087. updateBackground();
  1088. }
  1089. /**
  1090. * Syncs the presentation with the current DOM. Useful
  1091. * when new slides or control elements are added or when
  1092. * the configuration has changed.
  1093. */
  1094. function sync() {
  1095. // Subscribe to input
  1096. removeEventListeners();
  1097. addEventListeners();
  1098. // Force a layout to make sure the current config is accounted for
  1099. layout();
  1100. // Reflect the current autoSlide value
  1101. autoSlide = config.autoSlide;
  1102. // Start auto-sliding if it's enabled
  1103. cueAutoSlide();
  1104. // Re-create the slide backgrounds
  1105. createBackgrounds();
  1106. updateControls();
  1107. updateProgress();
  1108. updateBackground();
  1109. }
  1110. /**
  1111. * Updates one dimension of slides by showing the slide
  1112. * with the specified index.
  1113. *
  1114. * @param {String} selector A CSS selector that will fetch
  1115. * the group of slides we are working with
  1116. * @param {Number} index The index of the slide that should be
  1117. * shown
  1118. *
  1119. * @return {Number} The index of the slide that is now shown,
  1120. * might differ from the passed in index if it was out of
  1121. * bounds.
  1122. */
  1123. function updateSlides( selector, index ) {
  1124. // Select all slides and convert the NodeList result to
  1125. // an array
  1126. var slides = toArray( document.querySelectorAll( selector ) ),
  1127. slidesLength = slides.length;
  1128. if( slidesLength ) {
  1129. // Should the index loop?
  1130. if( config.loop ) {
  1131. index %= slidesLength;
  1132. if( index < 0 ) {
  1133. index = slidesLength + index;
  1134. }
  1135. }
  1136. // Enforce max and minimum index bounds
  1137. index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
  1138. for( var i = 0; i < slidesLength; i++ ) {
  1139. var element = slides[i];
  1140. // Optimization; hide all slides that are three or more steps
  1141. // away from the present slide
  1142. if( isOverview() === false ) {
  1143. // The distance loops so that it measures 1 between the first
  1144. // and last slides
  1145. var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
  1146. element.style.display = distance > 3 ? 'none' : 'block';
  1147. }
  1148. var reverse = config.rtl && !isVerticalSlide( element );
  1149. element.classList.remove( 'past' );
  1150. element.classList.remove( 'present' );
  1151. element.classList.remove( 'future' );
  1152. // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
  1153. element.setAttribute( 'hidden', '' );
  1154. if( i < index ) {
  1155. // Any element previous to index is given the 'past' class
  1156. element.classList.add( reverse ? 'future' : 'past' );
  1157. }
  1158. else if( i > index ) {
  1159. // Any element subsequent to index is given the 'future' class
  1160. element.classList.add( reverse ? 'past' : 'future' );
  1161. }
  1162. // If this element contains vertical slides
  1163. if( element.querySelector( 'section' ) ) {
  1164. element.classList.add( 'stack' );
  1165. }
  1166. }
  1167. // Mark the current slide as present
  1168. slides[index].classList.add( 'present' );
  1169. slides[index].removeAttribute( 'hidden' );
  1170. // If this slide has a state associated with it, add it
  1171. // onto the current state of the deck
  1172. var slideState = slides[index].getAttribute( 'data-state' );
  1173. if( slideState ) {
  1174. state = state.concat( slideState.split( ' ' ) );
  1175. }
  1176. // If this slide has a data-autoslide attribtue associated use this as
  1177. // autoSlide value otherwise use the global configured time
  1178. var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
  1179. if( slideAutoSlide ) {
  1180. autoSlide = parseInt( slideAutoSlide, 10 );
  1181. }
  1182. else {
  1183. autoSlide = config.autoSlide;
  1184. }
  1185. }
  1186. else {
  1187. // Since there are no slides we can't be anywhere beyond the
  1188. // zeroth index
  1189. index = 0;
  1190. }
  1191. return index;
  1192. }
  1193. /**
  1194. * Updates the progress bar to reflect the current slide.
  1195. */
  1196. function updateProgress() {
  1197. // Update progress if enabled
  1198. if( config.progress && dom.progress ) {
  1199. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1200. // The number of past and total slides
  1201. var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
  1202. var pastCount = 0;
  1203. // Step through all slides and count the past ones
  1204. mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
  1205. var horizontalSlide = horizontalSlides[i];
  1206. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
  1207. for( var j = 0; j < verticalSlides.length; j++ ) {
  1208. // Stop as soon as we arrive at the present
  1209. if( verticalSlides[j].classList.contains( 'present' ) ) {
  1210. break mainLoop;
  1211. }
  1212. pastCount++;
  1213. }
  1214. // Stop as soon as we arrive at the present
  1215. if( horizontalSlide.classList.contains( 'present' ) ) {
  1216. break;
  1217. }
  1218. // Don't count the wrapping section for vertical slides
  1219. if( horizontalSlide.classList.contains( 'stack' ) === false ) {
  1220. pastCount++;
  1221. }
  1222. }
  1223. dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
  1224. }
  1225. }
  1226. /**
  1227. * Updates the state of all control/navigation arrows.
  1228. */
  1229. function updateControls() {
  1230. if ( config.controls && dom.controls ) {
  1231. var routes = availableRoutes();
  1232. var fragments = availableFragments();
  1233. // Remove the 'enabled' class from all directions
  1234. dom.controlsLeft.concat( dom.controlsRight )
  1235. .concat( dom.controlsUp )
  1236. .concat( dom.controlsDown )
  1237. .concat( dom.controlsPrev )
  1238. .concat( dom.controlsNext ).forEach( function( node ) {
  1239. node.classList.remove( 'enabled' );
  1240. node.classList.remove( 'fragmented' );
  1241. } );
  1242. // Add the 'enabled' class to the available routes
  1243. if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1244. if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1245. if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1246. if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1247. // Prev/next buttons
  1248. if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1249. if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1250. // Highlight fragment directions
  1251. if( currentSlide ) {
  1252. // Always apply fragment decorator to prev/next buttons
  1253. if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1254. if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1255. // Apply fragment decorators to directional buttons based on
  1256. // what slide axis they are in
  1257. if( isVerticalSlide( currentSlide ) ) {
  1258. if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1259. if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1260. }
  1261. else {
  1262. if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1263. if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1264. }
  1265. }
  1266. }
  1267. }
  1268. /**
  1269. * Updates the background elements to reflect the current
  1270. * slide.
  1271. */
  1272. function updateBackground() {
  1273. // Update the classes of all backgrounds to match the
  1274. // states of their slides (past/present/future)
  1275. toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
  1276. // Reverse past/future classes when in RTL mode
  1277. var horizontalPast = config.rtl ? 'future' : 'past',
  1278. horizontalFuture = config.rtl ? 'past' : 'future';
  1279. backgroundh.className = 'slide-background ' + ( h < indexh ? horizontalPast : h > indexh ? horizontalFuture : 'present' );
  1280. toArray( backgroundh.childNodes ).forEach( function( backgroundv, v ) {
  1281. backgroundv.className = 'slide-background ' + ( v < indexv ? 'past' : v > indexv ? 'future' : 'present' );
  1282. } );
  1283. } );
  1284. // Allow the first background to apply without transition
  1285. setTimeout( function() {
  1286. dom.background.classList.remove( 'no-transition' );
  1287. }, 1 );
  1288. }
  1289. /**
  1290. * Determine what available routes there are for navigation.
  1291. *
  1292. * @return {Object} containing four booleans: left/right/up/down
  1293. */
  1294. function availableRoutes() {
  1295. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
  1296. verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
  1297. var routes = {
  1298. left: indexh > 0 || config.loop,
  1299. right: indexh < horizontalSlides.length - 1 || config.loop,
  1300. up: indexv > 0,
  1301. down: indexv < verticalSlides.length - 1
  1302. };
  1303. // reverse horizontal controls for rtl
  1304. if( config.rtl ) {
  1305. var left = routes.left;
  1306. routes.left = routes.right;
  1307. routes.right = left;
  1308. }
  1309. return routes;
  1310. }
  1311. /**
  1312. * Returns an object describing the available fragment
  1313. * directions.
  1314. *
  1315. * @return {Object} two boolean properties: prev/next
  1316. */
  1317. function availableFragments() {
  1318. if( currentSlide && config.fragments ) {
  1319. var fragments = currentSlide.querySelectorAll( '.fragment' );
  1320. var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
  1321. return {
  1322. prev: fragments.length - hiddenFragments.length > 0,
  1323. next: !!hiddenFragments.length
  1324. };
  1325. }
  1326. else {
  1327. return { prev: false, next: false };
  1328. }
  1329. }
  1330. /**
  1331. * Start playback of any embedded content inside of
  1332. * the targeted slide.
  1333. */
  1334. function startEmbeddedContent( slide ) {
  1335. if( slide ) {
  1336. // HTML5 media elements
  1337. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  1338. if( el.hasAttribute( 'data-autoplay' ) ) {
  1339. el.play();
  1340. }
  1341. } );
  1342. // YouTube embeds
  1343. toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
  1344. if( el.hasAttribute( 'data-autoplay' ) ) {
  1345. el.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  1346. }
  1347. });
  1348. }
  1349. }
  1350. /**
  1351. * Stop playback of any embedded content inside of
  1352. * the targeted slide.
  1353. */
  1354. function stopEmbeddedContent( slide ) {
  1355. if( slide ) {
  1356. // HTML5 media elements
  1357. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  1358. if( !el.hasAttribute( 'data-ignore' ) ) {
  1359. el.pause();
  1360. }
  1361. } );
  1362. // YouTube embeds
  1363. toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
  1364. if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
  1365. el.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
  1366. }
  1367. });
  1368. }
  1369. }
  1370. /**
  1371. * Reads the current URL (hash) and navigates accordingly.
  1372. */
  1373. function readURL() {
  1374. var hash = window.location.hash;
  1375. // Attempt to parse the hash as either an index or name
  1376. var bits = hash.slice( 2 ).split( '/' ),
  1377. name = hash.replace( /#|\//gi, '' );
  1378. // If the first bit is invalid and there is a name we can
  1379. // assume that this is a named link
  1380. if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
  1381. // Find the slide with the specified name
  1382. var element = document.querySelector( '#' + name );
  1383. if( element ) {
  1384. // Find the position of the named slide and navigate to it
  1385. var indices = Reveal.getIndices( element );
  1386. slide( indices.h, indices.v );
  1387. }
  1388. // If the slide doesn't exist, navigate to the current slide
  1389. else {
  1390. slide( indexh, indexv );
  1391. }
  1392. }
  1393. else {
  1394. // Read the index components of the hash
  1395. var h = parseInt( bits[0], 10 ) || 0,
  1396. v = parseInt( bits[1], 10 ) || 0;
  1397. slide( h, v );
  1398. }
  1399. }
  1400. /**
  1401. * Updates the page URL (hash) to reflect the current
  1402. * state.
  1403. *
  1404. * @param {Number} delay The time in ms to wait before
  1405. * writing the hash
  1406. */
  1407. function writeURL( delay ) {
  1408. if( config.history ) {
  1409. // Make sure there's never more than one timeout running
  1410. clearTimeout( writeURLTimeout );
  1411. // If a delay is specified, timeout this call
  1412. if( typeof delay === 'number' ) {
  1413. writeURLTimeout = setTimeout( writeURL, delay );
  1414. }
  1415. else {
  1416. var url = '/';
  1417. // If the current slide has an ID, use that as a named link
  1418. if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
  1419. url = '/' + currentSlide.getAttribute( 'id' );
  1420. }
  1421. // Otherwise use the /h/v index
  1422. else {
  1423. if( indexh > 0 || indexv > 0 ) url += indexh;
  1424. if( indexv > 0 ) url += '/' + indexv;
  1425. }
  1426. window.location.hash = url;
  1427. }
  1428. }
  1429. }
  1430. /**
  1431. * Retrieves the h/v location of the current, or specified,
  1432. * slide.
  1433. *
  1434. * @param {HTMLElement} slide If specified, the returned
  1435. * index will be for this slide rather than the currently
  1436. * active one
  1437. *
  1438. * @return {Object} { h: <int>, v: <int>, f: <int> }
  1439. */
  1440. function getIndices( slide ) {
  1441. // By default, return the current indices
  1442. var h = indexh,
  1443. v = indexv,
  1444. f;
  1445. // If a slide is specified, return the indices of that slide
  1446. if( slide ) {
  1447. var isVertical = isVerticalSlide( slide );
  1448. var slideh = isVertical ? slide.parentNode : slide;
  1449. // Select all horizontal slides
  1450. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1451. // Now that we know which the horizontal slide is, get its index
  1452. h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
  1453. // If this is a vertical slide, grab the vertical index
  1454. if( isVertical ) {
  1455. v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
  1456. }
  1457. }
  1458. if( !slide && currentSlide ) {
  1459. var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
  1460. if( visibleFragments.length ) {
  1461. f = visibleFragments.length;
  1462. }
  1463. }
  1464. return { h: h, v: v, f: f };
  1465. }
  1466. /**
  1467. * Navigate to the next slide fragment.
  1468. *
  1469. * @return {Boolean} true if there was a next fragment,
  1470. * false otherwise
  1471. */
  1472. function nextFragment() {
  1473. if( currentSlide && config.fragments ) {
  1474. var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment:not(.visible)' ) );
  1475. if( fragments.length ) {
  1476. // Find the index of the next fragment
  1477. var index = fragments[0].getAttribute( 'data-fragment-index' );
  1478. // Find all fragments with the same index
  1479. fragments = currentSlide.querySelectorAll( '.fragment[data-fragment-index="'+ index +'"]' );
  1480. toArray( fragments ).forEach( function( element ) {
  1481. element.classList.add( 'visible' );
  1482. // Notify subscribers of the change
  1483. dispatchEvent( 'fragmentshown', { fragment: element } );
  1484. } );
  1485. updateControls();
  1486. return true;
  1487. }
  1488. }
  1489. return false;
  1490. }
  1491. /**
  1492. * Navigate to the previous slide fragment.
  1493. *
  1494. * @return {Boolean} true if there was a previous fragment,
  1495. * false otherwise
  1496. */
  1497. function previousFragment() {
  1498. if( currentSlide && config.fragments ) {
  1499. var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) );
  1500. if( fragments.length ) {
  1501. // Find the index of the previous fragment
  1502. var index = fragments[ fragments.length - 1 ].getAttribute( 'data-fragment-index' );
  1503. // Find all fragments with the same index
  1504. fragments = currentSlide.querySelectorAll( '.fragment[data-fragment-index="'+ index +'"]' );
  1505. toArray( fragments ).forEach( function( f ) {
  1506. f.classList.remove( 'visible' );
  1507. // Notify subscribers of the change
  1508. dispatchEvent( 'fragmenthidden', { fragment: f } );
  1509. } );
  1510. updateControls();
  1511. return true;
  1512. }
  1513. }
  1514. return false;
  1515. }
  1516. /**
  1517. * Cues a new automated slide if enabled in the config.
  1518. */
  1519. function cueAutoSlide() {
  1520. clearTimeout( autoSlideTimeout );
  1521. // Cue the next auto-slide if enabled
  1522. if( autoSlide && !isPaused() && !isOverview() ) {
  1523. autoSlideTimeout = setTimeout( navigateNext, autoSlide );
  1524. }
  1525. }
  1526. /**
  1527. * Cancels any ongoing request to auto-slide.
  1528. */
  1529. function cancelAutoSlide() {
  1530. clearTimeout( autoSlideTimeout );
  1531. }
  1532. function navigateLeft() {
  1533. // Reverse for RTL
  1534. if( config.rtl ) {
  1535. if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
  1536. slide( indexh + 1 );
  1537. }
  1538. }
  1539. // Normal navigation
  1540. else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
  1541. slide( indexh - 1 );
  1542. }
  1543. }
  1544. function navigateRight() {
  1545. // Reverse for RTL
  1546. if( config.rtl ) {
  1547. if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
  1548. slide( indexh - 1 );
  1549. }
  1550. }
  1551. // Normal navigation
  1552. else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
  1553. slide( indexh + 1 );
  1554. }
  1555. }
  1556. function navigateUp() {
  1557. // Prioritize hiding fragments
  1558. if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
  1559. slide( indexh, indexv - 1 );
  1560. }
  1561. }
  1562. function navigateDown() {
  1563. // Prioritize revealing fragments
  1564. if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
  1565. slide( indexh, indexv + 1 );
  1566. }
  1567. }
  1568. /**
  1569. * Navigates backwards, prioritized in the following order:
  1570. * 1) Previous fragment
  1571. * 2) Previous vertical slide
  1572. * 3) Previous horizontal slide
  1573. */
  1574. function navigatePrev() {
  1575. // Prioritize revealing fragments
  1576. if( previousFragment() === false ) {
  1577. if( availableRoutes().up ) {
  1578. navigateUp();
  1579. }
  1580. else {
  1581. // Fetch the previous horizontal slide, if there is one
  1582. var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
  1583. if( previousSlide ) {
  1584. var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
  1585. var h = indexh - 1;
  1586. slide( h, v );
  1587. }
  1588. }
  1589. }
  1590. }
  1591. /**
  1592. * Same as #navigatePrev() but navigates forwards.
  1593. */
  1594. function navigateNext() {
  1595. // Prioritize revealing fragments
  1596. if( nextFragment() === false ) {
  1597. availableRoutes().down ? navigateDown() : navigateRight();
  1598. }
  1599. // If auto-sliding is enabled we need to cue up
  1600. // another timeout
  1601. cueAutoSlide();
  1602. }
  1603. // --------------------------------------------------------------------//
  1604. // ----------------------------- EVENTS -------------------------------//
  1605. // --------------------------------------------------------------------//
  1606. /**
  1607. * Handler for the document level 'keydown' event.
  1608. *
  1609. * @param {Object} event
  1610. */
  1611. function onDocumentKeyDown( event ) {
  1612. // Check if there's a focused element that could be using
  1613. // the keyboard
  1614. var activeElement = document.activeElement;
  1615. var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
  1616. // Disregard the event if there's a focused element or a
  1617. // keyboard modifier key is present
  1618. if( hasFocus || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
  1619. // While paused only allow "unpausing" keyboard events (b and .)
  1620. if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
  1621. return false;
  1622. }
  1623. var triggered = false;
  1624. // 1. User defined key bindings
  1625. if( typeof config.keyboard === 'object' ) {
  1626. for( var key in config.keyboard ) {
  1627. // Check if this binding matches the pressed key
  1628. if( parseInt( key, 10 ) === event.keyCode ) {
  1629. var value = config.keyboard[ key ];
  1630. // Calback function
  1631. if( typeof value === 'function' ) {
  1632. value.apply( null, [ event ] );
  1633. }
  1634. // String shortcuts to reveal.js API
  1635. else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
  1636. Reveal[ value ].call();
  1637. }
  1638. triggered = true;
  1639. }
  1640. }
  1641. }
  1642. // 2. System defined key bindings
  1643. if( triggered === false ) {
  1644. // Assume true and try to prove false
  1645. triggered = true;
  1646. switch( event.keyCode ) {
  1647. // p, page up
  1648. case 80: case 33: navigatePrev(); break;
  1649. // n, page down
  1650. case 78: case 34: navigateNext(); break;
  1651. // h, left
  1652. case 72: case 37: navigateLeft(); break;
  1653. // l, right
  1654. case 76: case 39: navigateRight(); break;
  1655. // k, up
  1656. case 75: case 38: navigateUp(); break;
  1657. // j, down
  1658. case 74: case 40: navigateDown(); break;
  1659. // home
  1660. case 36: slide( 0 ); break;
  1661. // end
  1662. case 35: slide( Number.MAX_VALUE ); break;
  1663. // space
  1664. case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
  1665. // return
  1666. case 13: isOverview() ? deactivateOverview() : triggered = false; break;
  1667. // b, period, Logitech presenter tools "black screen" button
  1668. case 66: case 190: case 191: togglePause(); break;
  1669. // f
  1670. case 70: enterFullscreen(); break;
  1671. default:
  1672. triggered = false;
  1673. }
  1674. }
  1675. // If the input resulted in a triggered action we should prevent
  1676. // the browsers default behavior
  1677. if( triggered ) {
  1678. event.preventDefault();
  1679. }
  1680. else if ( event.keyCode === 27 && supports3DTransforms ) {
  1681. toggleOverview();
  1682. event.preventDefault();
  1683. }
  1684. // If auto-sliding is enabled we need to cue up
  1685. // another timeout
  1686. cueAutoSlide();
  1687. }
  1688. /**
  1689. * Handler for the 'touchstart' event, enables support for
  1690. * swipe and pinch gestures.
  1691. */
  1692. function onTouchStart( event ) {
  1693. touch.startX = event.touches[0].clientX;
  1694. touch.startY = event.touches[0].clientY;
  1695. touch.startCount = event.touches.length;
  1696. // If there's two touches we need to memorize the distance
  1697. // between those two points to detect pinching
  1698. if( event.touches.length === 2 && config.overview ) {
  1699. touch.startSpan = distanceBetween( {
  1700. x: event.touches[1].clientX,
  1701. y: event.touches[1].clientY
  1702. }, {
  1703. x: touch.startX,
  1704. y: touch.startY
  1705. } );
  1706. }
  1707. }
  1708. /**
  1709. * Handler for the 'touchmove' event.
  1710. */
  1711. function onTouchMove( event ) {
  1712. // Each touch should only trigger one action
  1713. if( !touch.handled ) {
  1714. var currentX = event.touches[0].clientX;
  1715. var currentY = event.touches[0].clientY;
  1716. // If the touch started off with two points and still has
  1717. // two active touches; test for the pinch gesture
  1718. if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
  1719. // The current distance in pixels between the two touch points
  1720. var currentSpan = distanceBetween( {
  1721. x: event.touches[1].clientX,
  1722. y: event.touches[1].clientY
  1723. }, {
  1724. x: touch.startX,
  1725. y: touch.startY
  1726. } );
  1727. // If the span is larger than the desire amount we've got
  1728. // ourselves a pinch
  1729. if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
  1730. touch.handled = true;
  1731. if( currentSpan < touch.startSpan ) {
  1732. activateOverview();
  1733. }
  1734. else {
  1735. deactivateOverview();
  1736. }
  1737. }
  1738. event.preventDefault();
  1739. }
  1740. // There was only one touch point, look for a swipe
  1741. else if( event.touches.length === 1 && touch.startCount !== 2 ) {
  1742. var deltaX = currentX - touch.startX,
  1743. deltaY = currentY - touch.startY;
  1744. if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  1745. touch.handled = true;
  1746. navigateLeft();
  1747. }
  1748. else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  1749. touch.handled = true;
  1750. navigateRight();
  1751. }
  1752. else if( deltaY > touch.threshold ) {
  1753. touch.handled = true;
  1754. navigateUp();
  1755. }
  1756. else if( deltaY < -touch.threshold ) {
  1757. touch.handled = true;
  1758. navigateDown();
  1759. }
  1760. event.preventDefault();
  1761. }
  1762. }
  1763. // There's a bug with swiping on some Android devices unless
  1764. // the default action is always prevented
  1765. else if( navigator.userAgent.match( /android/gi ) ) {
  1766. event.preventDefault();
  1767. }
  1768. }
  1769. /**
  1770. * Handler for the 'touchend' event.
  1771. */
  1772. function onTouchEnd( event ) {
  1773. touch.handled = false;
  1774. }
  1775. /**
  1776. * Convert pointer down to touch start.
  1777. */
  1778. function onPointerDown( event ) {
  1779. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
  1780. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  1781. onTouchStart( event );
  1782. }
  1783. }
  1784. /**
  1785. * Convert pointer move to touch move.
  1786. */
  1787. function onPointerMove( event ) {
  1788. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
  1789. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  1790. onTouchMove( event );
  1791. }
  1792. }
  1793. /**
  1794. * Convert pointer up to touch end.
  1795. */
  1796. function onPointerUp( event ) {
  1797. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
  1798. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  1799. onTouchEnd( event );
  1800. }
  1801. }
  1802. /**
  1803. * Handles mouse wheel scrolling, throttled to avoid skipping
  1804. * multiple slides.
  1805. */
  1806. function onDocumentMouseScroll( event ) {
  1807. if( Date.now() - lastMouseWheelStep > 600 ) {
  1808. lastMouseWheelStep = Date.now();
  1809. var delta = event.detail || -event.wheelDelta;
  1810. if( delta > 0 ) {
  1811. navigateNext();
  1812. }
  1813. else {
  1814. navigatePrev();
  1815. }
  1816. }
  1817. }
  1818. /**
  1819. * Clicking on the progress bar results in a navigation to the
  1820. * closest approximate horizontal slide using this equation:
  1821. *
  1822. * ( clickX / presentationWidth ) * numberOfSlides
  1823. */
  1824. function onProgressClicked( event ) {
  1825. event.preventDefault();
  1826. var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
  1827. var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
  1828. slide( slideIndex );
  1829. }
  1830. /**
  1831. * Event handler for navigation control buttons.
  1832. */
  1833. function onNavigateLeftClicked( event ) { event.preventDefault(); navigateLeft(); }
  1834. function onNavigateRightClicked( event ) { event.preventDefault(); navigateRight(); }
  1835. function onNavigateUpClicked( event ) { event.preventDefault(); navigateUp(); }
  1836. function onNavigateDownClicked( event ) { event.preventDefault(); navigateDown(); }
  1837. function onNavigatePrevClicked( event ) { event.preventDefault(); navigatePrev(); }
  1838. function onNavigateNextClicked( event ) { event.preventDefault(); navigateNext(); }
  1839. /**
  1840. * Handler for the window level 'hashchange' event.
  1841. */
  1842. function onWindowHashChange( event ) {
  1843. readURL();
  1844. }
  1845. /**
  1846. * Handler for the window level 'resize' event.
  1847. */
  1848. function onWindowResize( event ) {
  1849. layout();
  1850. }
  1851. /**
  1852. * Invoked when a slide is and we're in the overview.
  1853. */
  1854. function onOverviewSlideClicked( event ) {
  1855. // TODO There's a bug here where the event listeners are not
  1856. // removed after deactivating the overview.
  1857. if( eventsAreBound && isOverview() ) {
  1858. event.preventDefault();
  1859. var element = event.target;
  1860. while( element && !element.nodeName.match( /section/gi ) ) {
  1861. element = element.parentNode;
  1862. }
  1863. if( element && !element.classList.contains( 'disabled' ) ) {
  1864. deactivateOverview();
  1865. if( element.nodeName.match( /section/gi ) ) {
  1866. var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
  1867. v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
  1868. slide( h, v );
  1869. }
  1870. }
  1871. }
  1872. }
  1873. /**
  1874. * Handles clicks on links that are set to preview in the
  1875. * iframe overlay.
  1876. */
  1877. function onPreviewLinkClicked( event ) {
  1878. var url = event.target.getAttribute( 'href' );
  1879. if( url ) {
  1880. openPreview( url );
  1881. event.preventDefault();
  1882. }
  1883. }
  1884. // --------------------------------------------------------------------//
  1885. // ------------------------------- API --------------------------------//
  1886. // --------------------------------------------------------------------//
  1887. return {
  1888. initialize: initialize,
  1889. configure: configure,
  1890. sync: sync,
  1891. // Navigation methods
  1892. slide: slide,
  1893. left: navigateLeft,
  1894. right: navigateRight,
  1895. up: navigateUp,
  1896. down: navigateDown,
  1897. prev: navigatePrev,
  1898. next: navigateNext,
  1899. prevFragment: previousFragment,
  1900. nextFragment: nextFragment,
  1901. // Deprecated aliases
  1902. navigateTo: slide,
  1903. navigateLeft: navigateLeft,
  1904. navigateRight: navigateRight,
  1905. navigateUp: navigateUp,
  1906. navigateDown: navigateDown,
  1907. navigatePrev: navigatePrev,
  1908. navigateNext: navigateNext,
  1909. // Forces an update in slide layout
  1910. layout: layout,
  1911. // Returns an object with the available routes as booleans (left/right/top/bottom)
  1912. availableRoutes: availableRoutes,
  1913. // Returns an object with the available fragments as booleans (prev/next)
  1914. availableFragments: availableFragments,
  1915. // Toggles the overview mode on/off
  1916. toggleOverview: toggleOverview,
  1917. // Toggles the "black screen" mode on/off
  1918. togglePause: togglePause,
  1919. // State checks
  1920. isOverview: isOverview,
  1921. isPaused: isPaused,
  1922. // Adds or removes all internal event listeners (such as keyboard)
  1923. addEventListeners: addEventListeners,
  1924. removeEventListeners: removeEventListeners,
  1925. // Returns the indices of the current, or specified, slide
  1926. getIndices: getIndices,
  1927. // Returns the slide at the specified index, y is optional
  1928. getSlide: function( x, y ) {
  1929. var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
  1930. var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
  1931. if( typeof y !== 'undefined' ) {
  1932. return verticalSlides ? verticalSlides[ y ] : undefined;
  1933. }
  1934. return horizontalSlide;
  1935. },
  1936. // Returns the previous slide element, may be null
  1937. getPreviousSlide: function() {
  1938. return previousSlide;
  1939. },
  1940. // Returns the current slide element
  1941. getCurrentSlide: function() {
  1942. return currentSlide;
  1943. },
  1944. // Returns the current scale of the presentation content
  1945. getScale: function() {
  1946. return scale;
  1947. },
  1948. // Returns the current configuration object
  1949. getConfig: function() {
  1950. return config;
  1951. },
  1952. // Helper method, retrieves query string as a key/value hash
  1953. getQueryHash: function() {
  1954. var query = {};
  1955. location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
  1956. query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
  1957. } );
  1958. return query;
  1959. },
  1960. // Returns true if we're currently on the first slide
  1961. isFirstSlide: function() {
  1962. return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
  1963. },
  1964. // Returns true if we're currently on the last slide
  1965. isLastSlide: function() {
  1966. if( currentSlide && currentSlide.classList.contains( '.stack' ) ) {
  1967. return currentSlide.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
  1968. }
  1969. else {
  1970. return document.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
  1971. }
  1972. },
  1973. // Forward event binding to the reveal DOM element
  1974. addEventListener: function( type, listener, useCapture ) {
  1975. if( 'addEventListener' in window ) {
  1976. ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
  1977. }
  1978. },
  1979. removeEventListener: function( type, listener, useCapture ) {
  1980. if( 'addEventListener' in window ) {
  1981. ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
  1982. }
  1983. }
  1984. };
  1985. })();