reveal.js 90 KB

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