reveal.js 89 KB

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