reveal.js 105 KB

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