reveal.js 71 KB

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