reveal.js 101 KB

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