reveal.js 68 KB

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