reveal.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921
  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|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.round( slideSize.width * ( 1 + config.margin ) ),
  336. pageHeight = Math.round( 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 WebKit so that content remains crisp
  956. if( /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. }
  1412. /**
  1413. * Resets all vertical slides so that only the first
  1414. * is visible.
  1415. */
  1416. function resetVerticalSlides() {
  1417. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1418. horizontalSlides.forEach( function( horizontalSlide ) {
  1419. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
  1420. verticalSlides.forEach( function( verticalSlide, y ) {
  1421. if( y > 0 ) {
  1422. verticalSlide.classList.remove( 'present' );
  1423. verticalSlide.classList.remove( 'past' );
  1424. verticalSlide.classList.add( 'future' );
  1425. }
  1426. } );
  1427. } );
  1428. }
  1429. /**
  1430. * Sorts and formats all of fragments in the
  1431. * presentation.
  1432. */
  1433. function sortAllFragments() {
  1434. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1435. horizontalSlides.forEach( function( horizontalSlide ) {
  1436. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
  1437. verticalSlides.forEach( function( verticalSlide, y ) {
  1438. sortFragments( verticalSlide.querySelectorAll( '.fragment' ) );
  1439. } );
  1440. if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) );
  1441. } );
  1442. }
  1443. /**
  1444. * Updates one dimension of slides by showing the slide
  1445. * with the specified index.
  1446. *
  1447. * @param {String} selector A CSS selector that will fetch
  1448. * the group of slides we are working with
  1449. * @param {Number} index The index of the slide that should be
  1450. * shown
  1451. *
  1452. * @return {Number} The index of the slide that is now shown,
  1453. * might differ from the passed in index if it was out of
  1454. * bounds.
  1455. */
  1456. function updateSlides( selector, index ) {
  1457. // Select all slides and convert the NodeList result to
  1458. // an array
  1459. var slides = toArray( document.querySelectorAll( selector ) ),
  1460. slidesLength = slides.length;
  1461. var printMode = isPrintingPDF();
  1462. if( slidesLength ) {
  1463. // Should the index loop?
  1464. if( config.loop ) {
  1465. index %= slidesLength;
  1466. if( index < 0 ) {
  1467. index = slidesLength + index;
  1468. }
  1469. }
  1470. // Enforce max and minimum index bounds
  1471. index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
  1472. for( var i = 0; i < slidesLength; i++ ) {
  1473. var element = slides[i];
  1474. var reverse = config.rtl && !isVerticalSlide( element );
  1475. element.classList.remove( 'past' );
  1476. element.classList.remove( 'present' );
  1477. element.classList.remove( 'future' );
  1478. // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
  1479. element.setAttribute( 'hidden', '' );
  1480. // If this element contains vertical slides
  1481. if( element.querySelector( 'section' ) ) {
  1482. element.classList.add( 'stack' );
  1483. }
  1484. // If we're printing static slides, all slides are "present"
  1485. if( printMode ) {
  1486. element.classList.add( 'present' );
  1487. continue;
  1488. }
  1489. if( i < index ) {
  1490. // Any element previous to index is given the 'past' class
  1491. element.classList.add( reverse ? 'future' : 'past' );
  1492. if( config.fragments ) {
  1493. var pastFragments = toArray( element.querySelectorAll( '.fragment' ) );
  1494. // Show all fragments on prior slides
  1495. while( pastFragments.length ) {
  1496. var pastFragment = pastFragments.pop();
  1497. pastFragment.classList.add( 'visible' );
  1498. pastFragment.classList.remove( 'current-fragment' );
  1499. }
  1500. }
  1501. }
  1502. else if( i > index ) {
  1503. // Any element subsequent to index is given the 'future' class
  1504. element.classList.add( reverse ? 'past' : 'future' );
  1505. if( config.fragments ) {
  1506. var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) );
  1507. // No fragments in future slides should be visible ahead of time
  1508. while( futureFragments.length ) {
  1509. var futureFragment = futureFragments.pop();
  1510. futureFragment.classList.remove( 'visible' );
  1511. futureFragment.classList.remove( 'current-fragment' );
  1512. }
  1513. }
  1514. }
  1515. }
  1516. // Mark the current slide as present
  1517. slides[index].classList.add( 'present' );
  1518. slides[index].removeAttribute( 'hidden' );
  1519. // If this slide has a state associated with it, add it
  1520. // onto the current state of the deck
  1521. var slideState = slides[index].getAttribute( 'data-state' );
  1522. if( slideState ) {
  1523. state = state.concat( slideState.split( ' ' ) );
  1524. }
  1525. }
  1526. else {
  1527. // Since there are no slides we can't be anywhere beyond the
  1528. // zeroth index
  1529. index = 0;
  1530. }
  1531. return index;
  1532. }
  1533. /**
  1534. * Optimization method; hide all slides that are far away
  1535. * from the present slide.
  1536. */
  1537. function updateSlidesVisibility() {
  1538. // Select all slides and convert the NodeList result to
  1539. // an array
  1540. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ),
  1541. horizontalSlidesLength = horizontalSlides.length,
  1542. distanceX,
  1543. distanceY;
  1544. if( horizontalSlidesLength ) {
  1545. // The number of steps away from the present slide that will
  1546. // be visible
  1547. var viewDistance = isOverview() ? 10 : config.viewDistance;
  1548. // Limit view distance on weaker devices
  1549. if( isMobileDevice ) {
  1550. viewDistance = isOverview() ? 6 : 2;
  1551. }
  1552. // Limit view distance on weaker devices
  1553. if( isPrintingPDF() ) {
  1554. viewDistance = Number.MAX_VALUE;
  1555. }
  1556. for( var x = 0; x < horizontalSlidesLength; x++ ) {
  1557. var horizontalSlide = horizontalSlides[x];
  1558. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
  1559. verticalSlidesLength = verticalSlides.length;
  1560. // Loops so that it measures 1 between the first and last slides
  1561. distanceX = Math.abs( ( indexh - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
  1562. // Show the horizontal slide if it's within the view distance
  1563. if( distanceX < viewDistance ) {
  1564. showSlide( horizontalSlide );
  1565. }
  1566. else {
  1567. hideSlide( horizontalSlide );
  1568. }
  1569. if( verticalSlidesLength ) {
  1570. var oy = getPreviousVerticalIndex( horizontalSlide );
  1571. for( var y = 0; y < verticalSlidesLength; y++ ) {
  1572. var verticalSlide = verticalSlides[y];
  1573. distanceY = x === indexh ? Math.abs( indexv - y ) : Math.abs( y - oy );
  1574. if( distanceX + distanceY < viewDistance ) {
  1575. showSlide( verticalSlide );
  1576. }
  1577. else {
  1578. hideSlide( verticalSlide );
  1579. }
  1580. }
  1581. }
  1582. }
  1583. }
  1584. }
  1585. /**
  1586. * Updates the progress bar to reflect the current slide.
  1587. */
  1588. function updateProgress() {
  1589. // Update progress if enabled
  1590. if( config.progress && dom.progress ) {
  1591. dom.progressbar.style.width = getProgress() * window.innerWidth + 'px';
  1592. }
  1593. }
  1594. /**
  1595. * Updates the slide number div to reflect the current slide.
  1596. */
  1597. function updateSlideNumber() {
  1598. // Update slide number if enabled
  1599. if( config.slideNumber && dom.slideNumber) {
  1600. // Display the number of the page using 'indexh - indexv' format
  1601. var indexString = indexh;
  1602. if( indexv > 0 ) {
  1603. indexString += ' - ' + indexv;
  1604. }
  1605. dom.slideNumber.innerHTML = indexString;
  1606. }
  1607. }
  1608. /**
  1609. * Updates the state of all control/navigation arrows.
  1610. */
  1611. function updateControls() {
  1612. var routes = availableRoutes();
  1613. var fragments = availableFragments();
  1614. // Remove the 'enabled' class from all directions
  1615. dom.controlsLeft.concat( dom.controlsRight )
  1616. .concat( dom.controlsUp )
  1617. .concat( dom.controlsDown )
  1618. .concat( dom.controlsPrev )
  1619. .concat( dom.controlsNext ).forEach( function( node ) {
  1620. node.classList.remove( 'enabled' );
  1621. node.classList.remove( 'fragmented' );
  1622. } );
  1623. // Add the 'enabled' class to the available routes
  1624. if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1625. if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1626. if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1627. if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1628. // Prev/next buttons
  1629. if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1630. if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1631. // Highlight fragment directions
  1632. if( currentSlide ) {
  1633. // Always apply fragment decorator to prev/next buttons
  1634. if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1635. if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1636. // Apply fragment decorators to directional buttons based on
  1637. // what slide axis they are in
  1638. if( isVerticalSlide( currentSlide ) ) {
  1639. if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1640. if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1641. }
  1642. else {
  1643. if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1644. if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1645. }
  1646. }
  1647. }
  1648. /**
  1649. * Updates the background elements to reflect the current
  1650. * slide.
  1651. *
  1652. * @param {Boolean} includeAll If true, the backgrounds of
  1653. * all vertical slides (not just the present) will be updated.
  1654. */
  1655. function updateBackground( includeAll ) {
  1656. var currentBackground = null;
  1657. // Reverse past/future classes when in RTL mode
  1658. var horizontalPast = config.rtl ? 'future' : 'past',
  1659. horizontalFuture = config.rtl ? 'past' : 'future';
  1660. // Update the classes of all backgrounds to match the
  1661. // states of their slides (past/present/future)
  1662. toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
  1663. backgroundh.classList.remove( 'past' );
  1664. backgroundh.classList.remove( 'present' );
  1665. backgroundh.classList.remove( 'future' );
  1666. if( h < indexh ) {
  1667. backgroundh.classList.add( horizontalPast );
  1668. }
  1669. else if ( h > indexh ) {
  1670. backgroundh.classList.add( horizontalFuture );
  1671. }
  1672. else {
  1673. backgroundh.classList.add( 'present' );
  1674. // Store a reference to the current background element
  1675. currentBackground = backgroundh;
  1676. }
  1677. if( includeAll || h === indexh ) {
  1678. toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) {
  1679. backgroundv.classList.remove( 'past' );
  1680. backgroundv.classList.remove( 'present' );
  1681. backgroundv.classList.remove( 'future' );
  1682. if( v < indexv ) {
  1683. backgroundv.classList.add( 'past' );
  1684. }
  1685. else if ( v > indexv ) {
  1686. backgroundv.classList.add( 'future' );
  1687. }
  1688. else {
  1689. backgroundv.classList.add( 'present' );
  1690. // Only if this is the present horizontal and vertical slide
  1691. if( h === indexh ) currentBackground = backgroundv;
  1692. }
  1693. } );
  1694. }
  1695. } );
  1696. // Stop any currently playing video background
  1697. if( previousBackground ) {
  1698. var previousVideo = previousBackground.querySelector( 'video' );
  1699. if( previousVideo ) previousVideo.pause();
  1700. }
  1701. if( currentBackground ) {
  1702. // Start video playback
  1703. var currentVideo = currentBackground.querySelector( 'video' );
  1704. if( currentVideo ) currentVideo.play();
  1705. // Don't transition between identical backgrounds. This
  1706. // prevents unwanted flicker.
  1707. var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
  1708. var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
  1709. if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) {
  1710. dom.background.classList.add( 'no-transition' );
  1711. }
  1712. previousBackground = currentBackground;
  1713. }
  1714. // Allow the first background to apply without transition
  1715. setTimeout( function() {
  1716. dom.background.classList.remove( 'no-transition' );
  1717. }, 1 );
  1718. }
  1719. /**
  1720. * Updates the position of the parallax background based
  1721. * on the current slide index.
  1722. */
  1723. function updateParallax() {
  1724. if( config.parallaxBackgroundImage ) {
  1725. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
  1726. verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
  1727. var backgroundSize = dom.background.style.backgroundSize.split( ' ' ),
  1728. backgroundWidth, backgroundHeight;
  1729. if( backgroundSize.length === 1 ) {
  1730. backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
  1731. }
  1732. else {
  1733. backgroundWidth = parseInt( backgroundSize[0], 10 );
  1734. backgroundHeight = parseInt( backgroundSize[1], 10 );
  1735. }
  1736. var slideWidth = dom.background.offsetWidth;
  1737. var horizontalSlideCount = horizontalSlides.length;
  1738. var horizontalOffset = -( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) * indexh;
  1739. var slideHeight = dom.background.offsetHeight;
  1740. var verticalSlideCount = verticalSlides.length;
  1741. var verticalOffset = verticalSlideCount > 1 ? -( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ) * indexv : 0;
  1742. dom.background.style.backgroundPosition = horizontalOffset + 'px ' + verticalOffset + 'px';
  1743. }
  1744. }
  1745. /**
  1746. * Called when the given slide is within the configured view
  1747. * distance. Shows the slide element and loads any content
  1748. * that is set to load lazily (data-src).
  1749. */
  1750. function showSlide( slide ) {
  1751. // Show the slide element
  1752. slide.style.display = 'block';
  1753. // Media elements with data-src attributes
  1754. toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src], iframe[data-src]' ) ).forEach( function( element ) {
  1755. element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
  1756. element.removeAttribute( 'data-src' );
  1757. } );
  1758. // Media elements with <source> children
  1759. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) {
  1760. var sources = 0;
  1761. toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) {
  1762. source.setAttribute( 'src', source.getAttribute( 'data-src' ) );
  1763. source.removeAttribute( 'data-src' );
  1764. sources += 1;
  1765. } );
  1766. // If we rewrote sources for this video/audio element, we need
  1767. // to manually tell it to load from its new origin
  1768. if( sources > 0 ) {
  1769. media.load();
  1770. }
  1771. } );
  1772. // Show the corresponding background element
  1773. var indices = getIndices( slide );
  1774. var background = getSlideBackground( indices.h, indices.v );
  1775. background.style.display = 'block';
  1776. // If the background contains media, load it
  1777. if( background.hasAttribute( 'data-loaded' ) === false ) {
  1778. background.setAttribute( 'data-loaded', 'true' );
  1779. var backgroundImage = slide.getAttribute( 'data-background-image' );
  1780. var backgroundVideo = slide.getAttribute( 'data-background-video' );
  1781. // Images
  1782. if( backgroundImage ) {
  1783. background.style.backgroundImage = 'url('+ backgroundImage +')';
  1784. }
  1785. // Videos
  1786. else if ( backgroundVideo ) {
  1787. var video = document.createElement( 'video' );
  1788. // Support comma separated lists of video sources
  1789. backgroundVideo.split( ',' ).forEach( function( source ) {
  1790. video.innerHTML += '<source src="'+ source +'">';
  1791. } );
  1792. background.appendChild( video );
  1793. }
  1794. }
  1795. }
  1796. /**
  1797. * Called when the given slide is moved outside of the
  1798. * configured view distance.
  1799. */
  1800. function hideSlide( slide ) {
  1801. // Hide the slide element
  1802. slide.style.display = 'none';
  1803. // Hide the corresponding background element
  1804. var indices = getIndices( slide );
  1805. var background = getSlideBackground( indices.h, indices.v );
  1806. background.style.display = 'none';
  1807. }
  1808. /**
  1809. * Determine what available routes there are for navigation.
  1810. *
  1811. * @return {Object} containing four booleans: left/right/up/down
  1812. */
  1813. function availableRoutes() {
  1814. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
  1815. verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
  1816. var routes = {
  1817. left: indexh > 0 || config.loop,
  1818. right: indexh < horizontalSlides.length - 1 || config.loop,
  1819. up: indexv > 0,
  1820. down: indexv < verticalSlides.length - 1
  1821. };
  1822. // reverse horizontal controls for rtl
  1823. if( config.rtl ) {
  1824. var left = routes.left;
  1825. routes.left = routes.right;
  1826. routes.right = left;
  1827. }
  1828. return routes;
  1829. }
  1830. /**
  1831. * Returns an object describing the available fragment
  1832. * directions.
  1833. *
  1834. * @return {Object} two boolean properties: prev/next
  1835. */
  1836. function availableFragments() {
  1837. if( currentSlide && config.fragments ) {
  1838. var fragments = currentSlide.querySelectorAll( '.fragment' );
  1839. var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
  1840. return {
  1841. prev: fragments.length - hiddenFragments.length > 0,
  1842. next: !!hiddenFragments.length
  1843. };
  1844. }
  1845. else {
  1846. return { prev: false, next: false };
  1847. }
  1848. }
  1849. /**
  1850. * Start playback of any embedded content inside of
  1851. * the targeted slide.
  1852. */
  1853. function startEmbeddedContent( slide ) {
  1854. if( slide && !isSpeakerNotes() ) {
  1855. // HTML5 media elements
  1856. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  1857. if( el.hasAttribute( 'data-autoplay' ) ) {
  1858. el.play();
  1859. }
  1860. } );
  1861. // iframe embeds
  1862. toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
  1863. el.contentWindow.postMessage( 'slide:start', '*' );
  1864. });
  1865. // YouTube embeds
  1866. toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
  1867. if( el.hasAttribute( 'data-autoplay' ) ) {
  1868. el.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
  1869. }
  1870. });
  1871. }
  1872. }
  1873. /**
  1874. * Stop playback of any embedded content inside of
  1875. * the targeted slide.
  1876. */
  1877. function stopEmbeddedContent( slide ) {
  1878. if( slide ) {
  1879. // HTML5 media elements
  1880. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  1881. if( !el.hasAttribute( 'data-ignore' ) ) {
  1882. el.pause();
  1883. }
  1884. } );
  1885. // iframe embeds
  1886. toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
  1887. el.contentWindow.postMessage( 'slide:stop', '*' );
  1888. });
  1889. // YouTube embeds
  1890. toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
  1891. if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
  1892. el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
  1893. }
  1894. });
  1895. }
  1896. }
  1897. /**
  1898. * Returns a value ranging from 0-1 that represents
  1899. * how far into the presentation we have navigated.
  1900. */
  1901. function getProgress() {
  1902. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1903. // The number of past and total slides
  1904. var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
  1905. var pastCount = 0;
  1906. // Step through all slides and count the past ones
  1907. mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
  1908. var horizontalSlide = horizontalSlides[i];
  1909. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
  1910. for( var j = 0; j < verticalSlides.length; j++ ) {
  1911. // Stop as soon as we arrive at the present
  1912. if( verticalSlides[j].classList.contains( 'present' ) ) {
  1913. break mainLoop;
  1914. }
  1915. pastCount++;
  1916. }
  1917. // Stop as soon as we arrive at the present
  1918. if( horizontalSlide.classList.contains( 'present' ) ) {
  1919. break;
  1920. }
  1921. // Don't count the wrapping section for vertical slides
  1922. if( horizontalSlide.classList.contains( 'stack' ) === false ) {
  1923. pastCount++;
  1924. }
  1925. }
  1926. if( currentSlide ) {
  1927. var allFragments = currentSlide.querySelectorAll( '.fragment' );
  1928. // If there are fragments in the current slide those should be
  1929. // accounted for in the progress.
  1930. if( allFragments.length > 0 ) {
  1931. var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
  1932. // This value represents how big a portion of the slide progress
  1933. // that is made up by its fragments (0-1)
  1934. var fragmentWeight = 0.9;
  1935. // Add fragment progress to the past slide count
  1936. pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight;
  1937. }
  1938. }
  1939. return pastCount / ( totalCount - 1 );
  1940. }
  1941. /**
  1942. * Checks if this presentation is running inside of the
  1943. * speaker notes window.
  1944. */
  1945. function isSpeakerNotes() {
  1946. return !!window.location.search.match( /receiver/gi );
  1947. }
  1948. /**
  1949. * Reads the current URL (hash) and navigates accordingly.
  1950. */
  1951. function readURL() {
  1952. var hash = window.location.hash;
  1953. // Attempt to parse the hash as either an index or name
  1954. var bits = hash.slice( 2 ).split( '/' ),
  1955. name = hash.replace( /#|\//gi, '' );
  1956. // If the first bit is invalid and there is a name we can
  1957. // assume that this is a named link
  1958. if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
  1959. var element;
  1960. try {
  1961. // Find the slide with the specified name
  1962. element = document.querySelector( '#' + name );
  1963. }
  1964. catch( e ) {
  1965. // If the ID is an invalid selector a harmless SyntaxError
  1966. // may be thrown here.
  1967. }
  1968. if( element ) {
  1969. // Find the position of the named slide and navigate to it
  1970. var indices = Reveal.getIndices( element );
  1971. slide( indices.h, indices.v );
  1972. }
  1973. // If the slide doesn't exist, navigate to the current slide
  1974. else {
  1975. slide( indexh || 0, indexv || 0 );
  1976. }
  1977. }
  1978. else {
  1979. // Read the index components of the hash
  1980. var h = parseInt( bits[0], 10 ) || 0,
  1981. v = parseInt( bits[1], 10 ) || 0;
  1982. if( h !== indexh || v !== indexv ) {
  1983. slide( h, v );
  1984. }
  1985. }
  1986. }
  1987. /**
  1988. * Updates the page URL (hash) to reflect the current
  1989. * state.
  1990. *
  1991. * @param {Number} delay The time in ms to wait before
  1992. * writing the hash
  1993. */
  1994. function writeURL( delay ) {
  1995. if( config.history ) {
  1996. // Make sure there's never more than one timeout running
  1997. clearTimeout( writeURLTimeout );
  1998. // If a delay is specified, timeout this call
  1999. if( typeof delay === 'number' ) {
  2000. writeURLTimeout = setTimeout( writeURL, delay );
  2001. }
  2002. else {
  2003. var url = '/';
  2004. // Attempt to create a named link based on the slide's ID
  2005. var id = currentSlide.getAttribute( 'id' );
  2006. if( id ) {
  2007. id = id.toLowerCase();
  2008. id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' );
  2009. }
  2010. // If the current slide has an ID, use that as a named link
  2011. if( currentSlide && typeof id === 'string' && id.length ) {
  2012. url = '/' + id;
  2013. }
  2014. // Otherwise use the /h/v index
  2015. else {
  2016. if( indexh > 0 || indexv > 0 ) url += indexh;
  2017. if( indexv > 0 ) url += '/' + indexv;
  2018. }
  2019. window.location.hash = url;
  2020. }
  2021. }
  2022. }
  2023. /**
  2024. * Retrieves the h/v location of the current, or specified,
  2025. * slide.
  2026. *
  2027. * @param {HTMLElement} slide If specified, the returned
  2028. * index will be for this slide rather than the currently
  2029. * active one
  2030. *
  2031. * @return {Object} { h: <int>, v: <int>, f: <int> }
  2032. */
  2033. function getIndices( slide ) {
  2034. // By default, return the current indices
  2035. var h = indexh,
  2036. v = indexv,
  2037. f;
  2038. // If a slide is specified, return the indices of that slide
  2039. if( slide ) {
  2040. var isVertical = isVerticalSlide( slide );
  2041. var slideh = isVertical ? slide.parentNode : slide;
  2042. // Select all horizontal slides
  2043. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  2044. // Now that we know which the horizontal slide is, get its index
  2045. h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
  2046. // Assume we're not vertical
  2047. v = 0;
  2048. // If this is a vertical slide, grab the vertical index
  2049. if( isVertical ) {
  2050. v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
  2051. }
  2052. }
  2053. if( !slide && currentSlide ) {
  2054. var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
  2055. if( hasFragments ) {
  2056. var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
  2057. f = visibleFragments.length - 1;
  2058. }
  2059. }
  2060. return { h: h, v: v, f: f };
  2061. }
  2062. /**
  2063. * Retrieves the total number of slides in this presentation.
  2064. */
  2065. function getTotalSlides() {
  2066. return document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
  2067. }
  2068. /**
  2069. * Returns the slide element matching the specified index.
  2070. */
  2071. function getSlide( x, y ) {
  2072. var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
  2073. var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
  2074. if( verticalSlides && verticalSlides.length && typeof y === 'number' ) {
  2075. return verticalSlides ? verticalSlides[ y ] : undefined;
  2076. }
  2077. return horizontalSlide;
  2078. }
  2079. /**
  2080. * Returns the background element for the given slide.
  2081. * All slides, even the ones with no background properties
  2082. * defined, have a background element so as long as the
  2083. * index is valid an element will be returned.
  2084. */
  2085. function getSlideBackground( x, y ) {
  2086. // When printing to PDF the slide backgrounds are nested
  2087. // inside of the slides
  2088. if( isPrintingPDF() ) {
  2089. var slide = getSlide( x, y );
  2090. return slide ? slide.querySelector( '.slide-background' ) : undefined;
  2091. }
  2092. var horizontalBackground = document.querySelectorAll( '.backgrounds>.slide-background' )[ x ];
  2093. var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' );
  2094. if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) {
  2095. return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined;
  2096. }
  2097. return horizontalBackground;
  2098. }
  2099. /**
  2100. * Retrieves the current state of the presentation as
  2101. * an object. This state can then be restored at any
  2102. * time.
  2103. */
  2104. function getState() {
  2105. var indices = getIndices();
  2106. return {
  2107. indexh: indices.h,
  2108. indexv: indices.v,
  2109. indexf: indices.f,
  2110. paused: isPaused(),
  2111. overview: isOverview()
  2112. };
  2113. }
  2114. /**
  2115. * Restores the presentation to the given state.
  2116. *
  2117. * @param {Object} state As generated by getState()
  2118. */
  2119. function setState( state ) {
  2120. if( typeof state === 'object' ) {
  2121. slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
  2122. var pausedFlag = deserialize( state.paused ),
  2123. overviewFlag = deserialize( state.overview );
  2124. if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
  2125. togglePause( pausedFlag );
  2126. }
  2127. if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) {
  2128. toggleOverview( overviewFlag );
  2129. }
  2130. }
  2131. }
  2132. /**
  2133. * Return a sorted fragments list, ordered by an increasing
  2134. * "data-fragment-index" attribute.
  2135. *
  2136. * Fragments will be revealed in the order that they are returned by
  2137. * this function, so you can use the index attributes to control the
  2138. * order of fragment appearance.
  2139. *
  2140. * To maintain a sensible default fragment order, fragments are presumed
  2141. * to be passed in document order. This function adds a "fragment-index"
  2142. * attribute to each node if such an attribute is not already present,
  2143. * and sets that attribute to an integer value which is the position of
  2144. * the fragment within the fragments list.
  2145. */
  2146. function sortFragments( fragments ) {
  2147. fragments = toArray( fragments );
  2148. var ordered = [],
  2149. unordered = [],
  2150. sorted = [];
  2151. // Group ordered and unordered elements
  2152. fragments.forEach( function( fragment, i ) {
  2153. if( fragment.hasAttribute( 'data-fragment-index' ) ) {
  2154. var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
  2155. if( !ordered[index] ) {
  2156. ordered[index] = [];
  2157. }
  2158. ordered[index].push( fragment );
  2159. }
  2160. else {
  2161. unordered.push( [ fragment ] );
  2162. }
  2163. } );
  2164. // Append fragments without explicit indices in their
  2165. // DOM order
  2166. ordered = ordered.concat( unordered );
  2167. // Manually count the index up per group to ensure there
  2168. // are no gaps
  2169. var index = 0;
  2170. // Push all fragments in their sorted order to an array,
  2171. // this flattens the groups
  2172. ordered.forEach( function( group ) {
  2173. group.forEach( function( fragment ) {
  2174. sorted.push( fragment );
  2175. fragment.setAttribute( 'data-fragment-index', index );
  2176. } );
  2177. index ++;
  2178. } );
  2179. return sorted;
  2180. }
  2181. /**
  2182. * Navigate to the specified slide fragment.
  2183. *
  2184. * @param {Number} index The index of the fragment that
  2185. * should be shown, -1 means all are invisible
  2186. * @param {Number} offset Integer offset to apply to the
  2187. * fragment index
  2188. *
  2189. * @return {Boolean} true if a change was made in any
  2190. * fragments visibility as part of this call
  2191. */
  2192. function navigateFragment( index, offset ) {
  2193. if( currentSlide && config.fragments ) {
  2194. var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
  2195. if( fragments.length ) {
  2196. // If no index is specified, find the current
  2197. if( typeof index !== 'number' ) {
  2198. var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
  2199. if( lastVisibleFragment ) {
  2200. index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
  2201. }
  2202. else {
  2203. index = -1;
  2204. }
  2205. }
  2206. // If an offset is specified, apply it to the index
  2207. if( typeof offset === 'number' ) {
  2208. index += offset;
  2209. }
  2210. var fragmentsShown = [],
  2211. fragmentsHidden = [];
  2212. toArray( fragments ).forEach( function( element, i ) {
  2213. if( element.hasAttribute( 'data-fragment-index' ) ) {
  2214. i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
  2215. }
  2216. // Visible fragments
  2217. if( i <= index ) {
  2218. if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
  2219. element.classList.add( 'visible' );
  2220. element.classList.remove( 'current-fragment' );
  2221. if( i === index ) {
  2222. element.classList.add( 'current-fragment' );
  2223. }
  2224. }
  2225. // Hidden fragments
  2226. else {
  2227. if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
  2228. element.classList.remove( 'visible' );
  2229. element.classList.remove( 'current-fragment' );
  2230. }
  2231. } );
  2232. if( fragmentsHidden.length ) {
  2233. dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
  2234. }
  2235. if( fragmentsShown.length ) {
  2236. dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
  2237. }
  2238. updateControls();
  2239. updateProgress();
  2240. return !!( fragmentsShown.length || fragmentsHidden.length );
  2241. }
  2242. }
  2243. return false;
  2244. }
  2245. /**
  2246. * Navigate to the next slide fragment.
  2247. *
  2248. * @return {Boolean} true if there was a next fragment,
  2249. * false otherwise
  2250. */
  2251. function nextFragment() {
  2252. return navigateFragment( null, 1 );
  2253. }
  2254. /**
  2255. * Navigate to the previous slide fragment.
  2256. *
  2257. * @return {Boolean} true if there was a previous fragment,
  2258. * false otherwise
  2259. */
  2260. function previousFragment() {
  2261. return navigateFragment( null, -1 );
  2262. }
  2263. /**
  2264. * Cues a new automated slide if enabled in the config.
  2265. */
  2266. function cueAutoSlide() {
  2267. cancelAutoSlide();
  2268. if( currentSlide ) {
  2269. var currentFragment = currentSlide.querySelector( '.current-fragment' );
  2270. var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null;
  2271. var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
  2272. var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
  2273. // Pick value in the following priority order:
  2274. // 1. Current fragment's data-autoslide
  2275. // 2. Current slide's data-autoslide
  2276. // 3. Parent slide's data-autoslide
  2277. // 4. Global autoSlide setting
  2278. if( fragmentAutoSlide ) {
  2279. autoSlide = parseInt( fragmentAutoSlide, 10 );
  2280. }
  2281. else if( slideAutoSlide ) {
  2282. autoSlide = parseInt( slideAutoSlide, 10 );
  2283. }
  2284. else if( parentAutoSlide ) {
  2285. autoSlide = parseInt( parentAutoSlide, 10 );
  2286. }
  2287. else {
  2288. autoSlide = config.autoSlide;
  2289. }
  2290. // If there are media elements with data-autoplay,
  2291. // automatically set the autoSlide duration to the
  2292. // length of that media
  2293. toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  2294. if( el.hasAttribute( 'data-autoplay' ) ) {
  2295. if( autoSlide && el.duration * 1000 > autoSlide ) {
  2296. autoSlide = ( el.duration * 1000 ) + 1000;
  2297. }
  2298. }
  2299. } );
  2300. // Cue the next auto-slide if:
  2301. // - There is an autoSlide value
  2302. // - Auto-sliding isn't paused by the user
  2303. // - The presentation isn't paused
  2304. // - The overview isn't active
  2305. // - The presentation isn't over
  2306. if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || config.loop === true ) ) {
  2307. autoSlideTimeout = setTimeout( navigateNext, autoSlide );
  2308. autoSlideStartTime = Date.now();
  2309. }
  2310. if( autoSlidePlayer ) {
  2311. autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
  2312. }
  2313. }
  2314. }
  2315. /**
  2316. * Cancels any ongoing request to auto-slide.
  2317. */
  2318. function cancelAutoSlide() {
  2319. clearTimeout( autoSlideTimeout );
  2320. autoSlideTimeout = -1;
  2321. }
  2322. function pauseAutoSlide() {
  2323. if( autoSlide && !autoSlidePaused ) {
  2324. autoSlidePaused = true;
  2325. dispatchEvent( 'autoslidepaused' );
  2326. clearTimeout( autoSlideTimeout );
  2327. if( autoSlidePlayer ) {
  2328. autoSlidePlayer.setPlaying( false );
  2329. }
  2330. }
  2331. }
  2332. function resumeAutoSlide() {
  2333. if( autoSlide && autoSlidePaused ) {
  2334. autoSlidePaused = false;
  2335. dispatchEvent( 'autoslideresumed' );
  2336. cueAutoSlide();
  2337. }
  2338. }
  2339. function navigateLeft() {
  2340. // Reverse for RTL
  2341. if( config.rtl ) {
  2342. if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
  2343. slide( indexh + 1 );
  2344. }
  2345. }
  2346. // Normal navigation
  2347. else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
  2348. slide( indexh - 1 );
  2349. }
  2350. }
  2351. function navigateRight() {
  2352. // Reverse for RTL
  2353. if( config.rtl ) {
  2354. if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
  2355. slide( indexh - 1 );
  2356. }
  2357. }
  2358. // Normal navigation
  2359. else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
  2360. slide( indexh + 1 );
  2361. }
  2362. }
  2363. function navigateUp() {
  2364. // Prioritize hiding fragments
  2365. if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
  2366. slide( indexh, indexv - 1 );
  2367. }
  2368. }
  2369. function navigateDown() {
  2370. // Prioritize revealing fragments
  2371. if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
  2372. slide( indexh, indexv + 1 );
  2373. }
  2374. }
  2375. /**
  2376. * Navigates backwards, prioritized in the following order:
  2377. * 1) Previous fragment
  2378. * 2) Previous vertical slide
  2379. * 3) Previous horizontal slide
  2380. */
  2381. function navigatePrev() {
  2382. // Prioritize revealing fragments
  2383. if( previousFragment() === false ) {
  2384. if( availableRoutes().up ) {
  2385. navigateUp();
  2386. }
  2387. else {
  2388. // Fetch the previous horizontal slide, if there is one
  2389. var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
  2390. if( previousSlide ) {
  2391. var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
  2392. var h = indexh - 1;
  2393. slide( h, v );
  2394. }
  2395. }
  2396. }
  2397. }
  2398. /**
  2399. * Same as #navigatePrev() but navigates forwards.
  2400. */
  2401. function navigateNext() {
  2402. // Prioritize revealing fragments
  2403. if( nextFragment() === false ) {
  2404. availableRoutes().down ? navigateDown() : navigateRight();
  2405. }
  2406. // If auto-sliding is enabled we need to cue up
  2407. // another timeout
  2408. cueAutoSlide();
  2409. }
  2410. // --------------------------------------------------------------------//
  2411. // ----------------------------- EVENTS -------------------------------//
  2412. // --------------------------------------------------------------------//
  2413. /**
  2414. * Called by all event handlers that are based on user
  2415. * input.
  2416. */
  2417. function onUserInput( event ) {
  2418. if( config.autoSlideStoppable ) {
  2419. pauseAutoSlide();
  2420. }
  2421. }
  2422. /**
  2423. * Handler for the document level 'keydown' event.
  2424. */
  2425. function onDocumentKeyDown( event ) {
  2426. // If there's a condition specified and it returns false,
  2427. // ignore this event
  2428. if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) {
  2429. return true;
  2430. }
  2431. // Remember if auto-sliding was paused so we can toggle it
  2432. var autoSlideWasPaused = autoSlidePaused;
  2433. onUserInput( event );
  2434. // Check if there's a focused element that could be using
  2435. // the keyboard
  2436. var activeElement = document.activeElement;
  2437. var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
  2438. // Disregard the event if there's a focused element or a
  2439. // keyboard modifier key is present
  2440. if( hasFocus || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
  2441. // While paused only allow "unpausing" keyboard events (b and .)
  2442. if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
  2443. return false;
  2444. }
  2445. var triggered = false;
  2446. // 1. User defined key bindings
  2447. if( typeof config.keyboard === 'object' ) {
  2448. for( var key in config.keyboard ) {
  2449. // Check if this binding matches the pressed key
  2450. if( parseInt( key, 10 ) === event.keyCode ) {
  2451. var value = config.keyboard[ key ];
  2452. // Callback function
  2453. if( typeof value === 'function' ) {
  2454. value.apply( null, [ event ] );
  2455. }
  2456. // String shortcuts to reveal.js API
  2457. else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
  2458. Reveal[ value ].call();
  2459. }
  2460. triggered = true;
  2461. }
  2462. }
  2463. }
  2464. // 2. System defined key bindings
  2465. if( triggered === false ) {
  2466. // Assume true and try to prove false
  2467. triggered = true;
  2468. switch( event.keyCode ) {
  2469. // p, page up
  2470. case 80: case 33: navigatePrev(); break;
  2471. // n, page down
  2472. case 78: case 34: navigateNext(); break;
  2473. // h, left
  2474. case 72: case 37: navigateLeft(); break;
  2475. // l, right
  2476. case 76: case 39: navigateRight(); break;
  2477. // k, up
  2478. case 75: case 38: navigateUp(); break;
  2479. // j, down
  2480. case 74: case 40: navigateDown(); break;
  2481. // home
  2482. case 36: slide( 0 ); break;
  2483. // end
  2484. case 35: slide( Number.MAX_VALUE ); break;
  2485. // space
  2486. case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
  2487. // return
  2488. case 13: isOverview() ? deactivateOverview() : triggered = false; break;
  2489. // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
  2490. case 58: case 59: case 66: case 190: case 191: togglePause(); break;
  2491. // f
  2492. case 70: enterFullscreen(); break;
  2493. // a
  2494. case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
  2495. default:
  2496. triggered = false;
  2497. }
  2498. }
  2499. // If the input resulted in a triggered action we should prevent
  2500. // the browsers default behavior
  2501. if( triggered ) {
  2502. event.preventDefault();
  2503. }
  2504. // ESC or O key
  2505. else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
  2506. if( dom.preview ) {
  2507. closePreview();
  2508. }
  2509. else {
  2510. toggleOverview();
  2511. }
  2512. event.preventDefault();
  2513. }
  2514. // If auto-sliding is enabled we need to cue up
  2515. // another timeout
  2516. cueAutoSlide();
  2517. }
  2518. /**
  2519. * Handler for the 'touchstart' event, enables support for
  2520. * swipe and pinch gestures.
  2521. */
  2522. function onTouchStart( event ) {
  2523. touch.startX = event.touches[0].clientX;
  2524. touch.startY = event.touches[0].clientY;
  2525. touch.startCount = event.touches.length;
  2526. // If there's two touches we need to memorize the distance
  2527. // between those two points to detect pinching
  2528. if( event.touches.length === 2 && config.overview ) {
  2529. touch.startSpan = distanceBetween( {
  2530. x: event.touches[1].clientX,
  2531. y: event.touches[1].clientY
  2532. }, {
  2533. x: touch.startX,
  2534. y: touch.startY
  2535. } );
  2536. }
  2537. }
  2538. /**
  2539. * Handler for the 'touchmove' event.
  2540. */
  2541. function onTouchMove( event ) {
  2542. // Each touch should only trigger one action
  2543. if( !touch.captured ) {
  2544. onUserInput( event );
  2545. var currentX = event.touches[0].clientX;
  2546. var currentY = event.touches[0].clientY;
  2547. // If the touch started with two points and still has
  2548. // two active touches; test for the pinch gesture
  2549. if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
  2550. // The current distance in pixels between the two touch points
  2551. var currentSpan = distanceBetween( {
  2552. x: event.touches[1].clientX,
  2553. y: event.touches[1].clientY
  2554. }, {
  2555. x: touch.startX,
  2556. y: touch.startY
  2557. } );
  2558. // If the span is larger than the desire amount we've got
  2559. // ourselves a pinch
  2560. if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
  2561. touch.captured = true;
  2562. if( currentSpan < touch.startSpan ) {
  2563. activateOverview();
  2564. }
  2565. else {
  2566. deactivateOverview();
  2567. }
  2568. }
  2569. event.preventDefault();
  2570. }
  2571. // There was only one touch point, look for a swipe
  2572. else if( event.touches.length === 1 && touch.startCount !== 2 ) {
  2573. var deltaX = currentX - touch.startX,
  2574. deltaY = currentY - touch.startY;
  2575. if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  2576. touch.captured = true;
  2577. navigateLeft();
  2578. }
  2579. else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  2580. touch.captured = true;
  2581. navigateRight();
  2582. }
  2583. else if( deltaY > touch.threshold ) {
  2584. touch.captured = true;
  2585. navigateUp();
  2586. }
  2587. else if( deltaY < -touch.threshold ) {
  2588. touch.captured = true;
  2589. navigateDown();
  2590. }
  2591. // If we're embedded, only block touch events if they have
  2592. // triggered an action
  2593. if( config.embedded ) {
  2594. if( touch.captured || isVerticalSlide( currentSlide ) ) {
  2595. event.preventDefault();
  2596. }
  2597. }
  2598. // Not embedded? Block them all to avoid needless tossing
  2599. // around of the viewport in iOS
  2600. else {
  2601. event.preventDefault();
  2602. }
  2603. }
  2604. }
  2605. // There's a bug with swiping on some Android devices unless
  2606. // the default action is always prevented
  2607. else if( navigator.userAgent.match( /android/gi ) ) {
  2608. event.preventDefault();
  2609. }
  2610. }
  2611. /**
  2612. * Handler for the 'touchend' event.
  2613. */
  2614. function onTouchEnd( event ) {
  2615. touch.captured = false;
  2616. }
  2617. /**
  2618. * Convert pointer down to touch start.
  2619. */
  2620. function onPointerDown( event ) {
  2621. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
  2622. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2623. onTouchStart( event );
  2624. }
  2625. }
  2626. /**
  2627. * Convert pointer move to touch move.
  2628. */
  2629. function onPointerMove( event ) {
  2630. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
  2631. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2632. onTouchMove( event );
  2633. }
  2634. }
  2635. /**
  2636. * Convert pointer up to touch end.
  2637. */
  2638. function onPointerUp( event ) {
  2639. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
  2640. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2641. onTouchEnd( event );
  2642. }
  2643. }
  2644. /**
  2645. * Handles mouse wheel scrolling, throttled to avoid skipping
  2646. * multiple slides.
  2647. */
  2648. function onDocumentMouseScroll( event ) {
  2649. if( Date.now() - lastMouseWheelStep > 600 ) {
  2650. lastMouseWheelStep = Date.now();
  2651. var delta = event.detail || -event.wheelDelta;
  2652. if( delta > 0 ) {
  2653. navigateNext();
  2654. }
  2655. else {
  2656. navigatePrev();
  2657. }
  2658. }
  2659. }
  2660. /**
  2661. * Clicking on the progress bar results in a navigation to the
  2662. * closest approximate horizontal slide using this equation:
  2663. *
  2664. * ( clickX / presentationWidth ) * numberOfSlides
  2665. */
  2666. function onProgressClicked( event ) {
  2667. onUserInput( event );
  2668. event.preventDefault();
  2669. var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
  2670. var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
  2671. slide( slideIndex );
  2672. }
  2673. /**
  2674. * Event handler for navigation control buttons.
  2675. */
  2676. function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
  2677. function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
  2678. function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
  2679. function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
  2680. function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
  2681. function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
  2682. /**
  2683. * Handler for the window level 'hashchange' event.
  2684. */
  2685. function onWindowHashChange( event ) {
  2686. readURL();
  2687. }
  2688. /**
  2689. * Handler for the window level 'resize' event.
  2690. */
  2691. function onWindowResize( event ) {
  2692. layout();
  2693. }
  2694. /**
  2695. * Handle for the window level 'visibilitychange' event.
  2696. */
  2697. function onPageVisibilityChange( event ) {
  2698. var isHidden = document.webkitHidden ||
  2699. document.msHidden ||
  2700. document.hidden;
  2701. // If, after clicking a link or similar and we're coming back,
  2702. // focus the document.body to ensure we can use keyboard shortcuts
  2703. if( isHidden === false && document.activeElement !== document.body ) {
  2704. document.activeElement.blur();
  2705. document.body.focus();
  2706. }
  2707. }
  2708. /**
  2709. * Invoked when a slide is and we're in the overview.
  2710. */
  2711. function onOverviewSlideClicked( event ) {
  2712. // TODO There's a bug here where the event listeners are not
  2713. // removed after deactivating the overview.
  2714. if( eventsAreBound && isOverview() ) {
  2715. event.preventDefault();
  2716. var element = event.target;
  2717. while( element && !element.nodeName.match( /section/gi ) ) {
  2718. element = element.parentNode;
  2719. }
  2720. if( element && !element.classList.contains( 'disabled' ) ) {
  2721. deactivateOverview();
  2722. if( element.nodeName.match( /section/gi ) ) {
  2723. var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
  2724. v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
  2725. slide( h, v );
  2726. }
  2727. }
  2728. }
  2729. }
  2730. /**
  2731. * Handles clicks on links that are set to preview in the
  2732. * iframe overlay.
  2733. */
  2734. function onPreviewLinkClicked( event ) {
  2735. var url = event.target.getAttribute( 'href' );
  2736. if( url ) {
  2737. openPreview( url );
  2738. event.preventDefault();
  2739. }
  2740. }
  2741. /**
  2742. * Handles click on the auto-sliding controls element.
  2743. */
  2744. function onAutoSlidePlayerClick( event ) {
  2745. // Replay
  2746. if( Reveal.isLastSlide() && config.loop === false ) {
  2747. slide( 0, 0 );
  2748. resumeAutoSlide();
  2749. }
  2750. // Resume
  2751. else if( autoSlidePaused ) {
  2752. resumeAutoSlide();
  2753. }
  2754. // Pause
  2755. else {
  2756. pauseAutoSlide();
  2757. }
  2758. }
  2759. // --------------------------------------------------------------------//
  2760. // ------------------------ PLAYBACK COMPONENT ------------------------//
  2761. // --------------------------------------------------------------------//
  2762. /**
  2763. * Constructor for the playback component, which displays
  2764. * play/pause/progress controls.
  2765. *
  2766. * @param {HTMLElement} container The component will append
  2767. * itself to this
  2768. * @param {Function} progressCheck A method which will be
  2769. * called frequently to get the current progress on a range
  2770. * of 0-1
  2771. */
  2772. function Playback( container, progressCheck ) {
  2773. // Cosmetics
  2774. this.diameter = 50;
  2775. this.thickness = 3;
  2776. // Flags if we are currently playing
  2777. this.playing = false;
  2778. // Current progress on a 0-1 range
  2779. this.progress = 0;
  2780. // Used to loop the animation smoothly
  2781. this.progressOffset = 1;
  2782. this.container = container;
  2783. this.progressCheck = progressCheck;
  2784. this.canvas = document.createElement( 'canvas' );
  2785. this.canvas.className = 'playback';
  2786. this.canvas.width = this.diameter;
  2787. this.canvas.height = this.diameter;
  2788. this.context = this.canvas.getContext( '2d' );
  2789. this.container.appendChild( this.canvas );
  2790. this.render();
  2791. }
  2792. Playback.prototype.setPlaying = function( value ) {
  2793. var wasPlaying = this.playing;
  2794. this.playing = value;
  2795. // Start repainting if we weren't already
  2796. if( !wasPlaying && this.playing ) {
  2797. this.animate();
  2798. }
  2799. else {
  2800. this.render();
  2801. }
  2802. };
  2803. Playback.prototype.animate = function() {
  2804. var progressBefore = this.progress;
  2805. this.progress = this.progressCheck();
  2806. // When we loop, offset the progress so that it eases
  2807. // smoothly rather than immediately resetting
  2808. if( progressBefore > 0.8 && this.progress < 0.2 ) {
  2809. this.progressOffset = this.progress;
  2810. }
  2811. this.render();
  2812. if( this.playing ) {
  2813. features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
  2814. }
  2815. };
  2816. /**
  2817. * Renders the current progress and playback state.
  2818. */
  2819. Playback.prototype.render = function() {
  2820. var progress = this.playing ? this.progress : 0,
  2821. radius = ( this.diameter / 2 ) - this.thickness,
  2822. x = this.diameter / 2,
  2823. y = this.diameter / 2,
  2824. iconSize = 14;
  2825. // Ease towards 1
  2826. this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
  2827. var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
  2828. var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
  2829. this.context.save();
  2830. this.context.clearRect( 0, 0, this.diameter, this.diameter );
  2831. // Solid background color
  2832. this.context.beginPath();
  2833. this.context.arc( x, y, radius + 2, 0, Math.PI * 2, false );
  2834. this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
  2835. this.context.fill();
  2836. // Draw progress track
  2837. this.context.beginPath();
  2838. this.context.arc( x, y, radius, 0, Math.PI * 2, false );
  2839. this.context.lineWidth = this.thickness;
  2840. this.context.strokeStyle = '#666';
  2841. this.context.stroke();
  2842. if( this.playing ) {
  2843. // Draw progress on top of track
  2844. this.context.beginPath();
  2845. this.context.arc( x, y, radius, startAngle, endAngle, false );
  2846. this.context.lineWidth = this.thickness;
  2847. this.context.strokeStyle = '#fff';
  2848. this.context.stroke();
  2849. }
  2850. this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
  2851. // Draw play/pause icons
  2852. if( this.playing ) {
  2853. this.context.fillStyle = '#fff';
  2854. this.context.fillRect( 0, 0, iconSize / 2 - 2, iconSize );
  2855. this.context.fillRect( iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize );
  2856. }
  2857. else {
  2858. this.context.beginPath();
  2859. this.context.translate( 2, 0 );
  2860. this.context.moveTo( 0, 0 );
  2861. this.context.lineTo( iconSize - 2, iconSize / 2 );
  2862. this.context.lineTo( 0, iconSize );
  2863. this.context.fillStyle = '#fff';
  2864. this.context.fill();
  2865. }
  2866. this.context.restore();
  2867. };
  2868. Playback.prototype.on = function( type, listener ) {
  2869. this.canvas.addEventListener( type, listener, false );
  2870. };
  2871. Playback.prototype.off = function( type, listener ) {
  2872. this.canvas.removeEventListener( type, listener, false );
  2873. };
  2874. Playback.prototype.destroy = function() {
  2875. this.playing = false;
  2876. if( this.canvas.parentNode ) {
  2877. this.container.removeChild( this.canvas );
  2878. }
  2879. };
  2880. // --------------------------------------------------------------------//
  2881. // ------------------------------- API --------------------------------//
  2882. // --------------------------------------------------------------------//
  2883. Reveal = {
  2884. initialize: initialize,
  2885. configure: configure,
  2886. sync: sync,
  2887. // Navigation methods
  2888. slide: slide,
  2889. left: navigateLeft,
  2890. right: navigateRight,
  2891. up: navigateUp,
  2892. down: navigateDown,
  2893. prev: navigatePrev,
  2894. next: navigateNext,
  2895. // Fragment methods
  2896. navigateFragment: navigateFragment,
  2897. prevFragment: previousFragment,
  2898. nextFragment: nextFragment,
  2899. // Deprecated aliases
  2900. navigateTo: slide,
  2901. navigateLeft: navigateLeft,
  2902. navigateRight: navigateRight,
  2903. navigateUp: navigateUp,
  2904. navigateDown: navigateDown,
  2905. navigatePrev: navigatePrev,
  2906. navigateNext: navigateNext,
  2907. // Forces an update in slide layout
  2908. layout: layout,
  2909. // Returns an object with the available routes as booleans (left/right/top/bottom)
  2910. availableRoutes: availableRoutes,
  2911. // Returns an object with the available fragments as booleans (prev/next)
  2912. availableFragments: availableFragments,
  2913. // Toggles the overview mode on/off
  2914. toggleOverview: toggleOverview,
  2915. // Toggles the "black screen" mode on/off
  2916. togglePause: togglePause,
  2917. // Toggles the auto slide mode on/off
  2918. toggleAutoSlide: toggleAutoSlide,
  2919. // State checks
  2920. isOverview: isOverview,
  2921. isPaused: isPaused,
  2922. isAutoSliding: isAutoSliding,
  2923. // Adds or removes all internal event listeners (such as keyboard)
  2924. addEventListeners: addEventListeners,
  2925. removeEventListeners: removeEventListeners,
  2926. // Facility for persisting and restoring the presentation state
  2927. getState: getState,
  2928. setState: setState,
  2929. // Presentation progress on range of 0-1
  2930. getProgress: getProgress,
  2931. // Returns the indices of the current, or specified, slide
  2932. getIndices: getIndices,
  2933. getTotalSlides: getTotalSlides,
  2934. // Returns the slide element at the specified index
  2935. getSlide: getSlide,
  2936. // Returns the slide background element at the specified index
  2937. getSlideBackground: getSlideBackground,
  2938. // Returns the previous slide element, may be null
  2939. getPreviousSlide: function() {
  2940. return previousSlide;
  2941. },
  2942. // Returns the current slide element
  2943. getCurrentSlide: function() {
  2944. return currentSlide;
  2945. },
  2946. // Returns the current scale of the presentation content
  2947. getScale: function() {
  2948. return scale;
  2949. },
  2950. // Returns the current configuration object
  2951. getConfig: function() {
  2952. return config;
  2953. },
  2954. // Helper method, retrieves query string as a key/value hash
  2955. getQueryHash: function() {
  2956. var query = {};
  2957. location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) {
  2958. query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
  2959. } );
  2960. // Basic deserialization
  2961. for( var i in query ) {
  2962. var value = query[ i ];
  2963. query[ i ] = deserialize( unescape( value ) );
  2964. }
  2965. return query;
  2966. },
  2967. // Returns true if we're currently on the first slide
  2968. isFirstSlide: function() {
  2969. return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
  2970. },
  2971. // Returns true if we're currently on the last slide
  2972. isLastSlide: function() {
  2973. if( currentSlide ) {
  2974. // Does this slide has next a sibling?
  2975. if( currentSlide.nextElementSibling ) return false;
  2976. // If it's vertical, does its parent have a next sibling?
  2977. if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
  2978. return true;
  2979. }
  2980. return false;
  2981. },
  2982. // Checks if reveal.js has been loaded and is ready for use
  2983. isReady: function() {
  2984. return loaded;
  2985. },
  2986. // Forward event binding to the reveal DOM element
  2987. addEventListener: function( type, listener, useCapture ) {
  2988. if( 'addEventListener' in window ) {
  2989. ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
  2990. }
  2991. },
  2992. removeEventListener: function( type, listener, useCapture ) {
  2993. if( 'addEventListener' in window ) {
  2994. ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
  2995. }
  2996. },
  2997. // Programatically triggers a keyboard event
  2998. triggerKey: function( keyCode ) {
  2999. onDocumentKeyDown( { keyCode: keyCode } );
  3000. }
  3001. };
  3002. return Reveal;
  3003. }));