reveal.js 68 KB

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