reveal.js 88 KB

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