reveal.js 103 KB

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