reveal.js 104 KB

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