reveal.js 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842
  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 <source> children
  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. function getSlide( x, y ) {
  2015. var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
  2016. var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
  2017. if( typeof y === 'number' ) {
  2018. return verticalSlides ? verticalSlides[ y ] : undefined;
  2019. }
  2020. return horizontalSlide;
  2021. }
  2022. /**
  2023. * Returns the background element for the given slide.
  2024. * All slides, even the ones with no background properties
  2025. * defined, have a background element so this never returns
  2026. * null.
  2027. */
  2028. function getSlideBackground( x, y ) {
  2029. var horizontalBackground = document.querySelectorAll( '.backgrounds>.slide-background' )[ x ];
  2030. var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' );
  2031. if( typeof y === 'number' ) {
  2032. return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined;
  2033. }
  2034. return horizontalBackground;
  2035. }
  2036. /**
  2037. * Retrieves the current state of the presentation as
  2038. * an object. This state can then be restored at any
  2039. * time.
  2040. */
  2041. function getState() {
  2042. var indices = getIndices();
  2043. return {
  2044. indexh: indices.h,
  2045. indexv: indices.v,
  2046. indexf: indices.f,
  2047. paused: isPaused(),
  2048. overview: isOverview()
  2049. };
  2050. }
  2051. /**
  2052. * Restores the presentation to the given state.
  2053. *
  2054. * @param {Object} state As generated by getState()
  2055. */
  2056. function setState( state ) {
  2057. if( typeof state === 'object' ) {
  2058. slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
  2059. var pausedFlag = deserialize( state.paused ),
  2060. overviewFlag = deserialize( state.overview );
  2061. if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
  2062. togglePause( pausedFlag );
  2063. }
  2064. if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) {
  2065. toggleOverview( overviewFlag );
  2066. }
  2067. }
  2068. }
  2069. /**
  2070. * Return a sorted fragments list, ordered by an increasing
  2071. * "data-fragment-index" attribute.
  2072. *
  2073. * Fragments will be revealed in the order that they are returned by
  2074. * this function, so you can use the index attributes to control the
  2075. * order of fragment appearance.
  2076. *
  2077. * To maintain a sensible default fragment order, fragments are presumed
  2078. * to be passed in document order. This function adds a "fragment-index"
  2079. * attribute to each node if such an attribute is not already present,
  2080. * and sets that attribute to an integer value which is the position of
  2081. * the fragment within the fragments list.
  2082. */
  2083. function sortFragments( fragments ) {
  2084. fragments = toArray( fragments );
  2085. var ordered = [],
  2086. unordered = [],
  2087. sorted = [];
  2088. // Group ordered and unordered elements
  2089. fragments.forEach( function( fragment, i ) {
  2090. if( fragment.hasAttribute( 'data-fragment-index' ) ) {
  2091. var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
  2092. if( !ordered[index] ) {
  2093. ordered[index] = [];
  2094. }
  2095. ordered[index].push( fragment );
  2096. }
  2097. else {
  2098. unordered.push( [ fragment ] );
  2099. }
  2100. } );
  2101. // Append fragments without explicit indices in their
  2102. // DOM order
  2103. ordered = ordered.concat( unordered );
  2104. // Manually count the index up per group to ensure there
  2105. // are no gaps
  2106. var index = 0;
  2107. // Push all fragments in their sorted order to an array,
  2108. // this flattens the groups
  2109. ordered.forEach( function( group ) {
  2110. group.forEach( function( fragment ) {
  2111. sorted.push( fragment );
  2112. fragment.setAttribute( 'data-fragment-index', index );
  2113. } );
  2114. index ++;
  2115. } );
  2116. return sorted;
  2117. }
  2118. /**
  2119. * Navigate to the specified slide fragment.
  2120. *
  2121. * @param {Number} index The index of the fragment that
  2122. * should be shown, -1 means all are invisible
  2123. * @param {Number} offset Integer offset to apply to the
  2124. * fragment index
  2125. *
  2126. * @return {Boolean} true if a change was made in any
  2127. * fragments visibility as part of this call
  2128. */
  2129. function navigateFragment( index, offset ) {
  2130. if( currentSlide && config.fragments ) {
  2131. var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
  2132. if( fragments.length ) {
  2133. // If no index is specified, find the current
  2134. if( typeof index !== 'number' ) {
  2135. var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
  2136. if( lastVisibleFragment ) {
  2137. index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
  2138. }
  2139. else {
  2140. index = -1;
  2141. }
  2142. }
  2143. // If an offset is specified, apply it to the index
  2144. if( typeof offset === 'number' ) {
  2145. index += offset;
  2146. }
  2147. var fragmentsShown = [],
  2148. fragmentsHidden = [];
  2149. toArray( fragments ).forEach( function( element, i ) {
  2150. if( element.hasAttribute( 'data-fragment-index' ) ) {
  2151. i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
  2152. }
  2153. // Visible fragments
  2154. if( i <= index ) {
  2155. if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
  2156. element.classList.add( 'visible' );
  2157. element.classList.remove( 'current-fragment' );
  2158. if( i === index ) {
  2159. element.classList.add( 'current-fragment' );
  2160. }
  2161. }
  2162. // Hidden fragments
  2163. else {
  2164. if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
  2165. element.classList.remove( 'visible' );
  2166. element.classList.remove( 'current-fragment' );
  2167. }
  2168. } );
  2169. if( fragmentsHidden.length ) {
  2170. dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
  2171. }
  2172. if( fragmentsShown.length ) {
  2173. dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
  2174. }
  2175. updateControls();
  2176. updateProgress();
  2177. return !!( fragmentsShown.length || fragmentsHidden.length );
  2178. }
  2179. }
  2180. return false;
  2181. }
  2182. /**
  2183. * Navigate to the next slide fragment.
  2184. *
  2185. * @return {Boolean} true if there was a next fragment,
  2186. * false otherwise
  2187. */
  2188. function nextFragment() {
  2189. return navigateFragment( null, 1 );
  2190. }
  2191. /**
  2192. * Navigate to the previous slide fragment.
  2193. *
  2194. * @return {Boolean} true if there was a previous fragment,
  2195. * false otherwise
  2196. */
  2197. function previousFragment() {
  2198. return navigateFragment( null, -1 );
  2199. }
  2200. /**
  2201. * Cues a new automated slide if enabled in the config.
  2202. */
  2203. function cueAutoSlide() {
  2204. cancelAutoSlide();
  2205. if( currentSlide ) {
  2206. var currentFragment = currentSlide.querySelector( '.current-fragment' );
  2207. var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null;
  2208. var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
  2209. var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
  2210. // Pick value in the following priority order:
  2211. // 1. Current fragment's data-autoslide
  2212. // 2. Current slide's data-autoslide
  2213. // 3. Parent slide's data-autoslide
  2214. // 4. Global autoSlide setting
  2215. if( fragmentAutoSlide ) {
  2216. autoSlide = parseInt( fragmentAutoSlide, 10 );
  2217. }
  2218. else if( slideAutoSlide ) {
  2219. autoSlide = parseInt( slideAutoSlide, 10 );
  2220. }
  2221. else if( parentAutoSlide ) {
  2222. autoSlide = parseInt( parentAutoSlide, 10 );
  2223. }
  2224. else {
  2225. autoSlide = config.autoSlide;
  2226. }
  2227. // If there are media elements with data-autoplay,
  2228. // automatically set the autoSlide duration to the
  2229. // length of that media
  2230. toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  2231. if( el.hasAttribute( 'data-autoplay' ) ) {
  2232. if( autoSlide && el.duration * 1000 > autoSlide ) {
  2233. autoSlide = ( el.duration * 1000 ) + 1000;
  2234. }
  2235. }
  2236. } );
  2237. // Cue the next auto-slide if:
  2238. // - There is an autoSlide value
  2239. // - Auto-sliding isn't paused by the user
  2240. // - The presentation isn't paused
  2241. // - The overview isn't active
  2242. // - The presentation isn't over
  2243. if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || config.loop === true ) ) {
  2244. autoSlideTimeout = setTimeout( navigateNext, autoSlide );
  2245. autoSlideStartTime = Date.now();
  2246. }
  2247. if( autoSlidePlayer ) {
  2248. autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
  2249. }
  2250. }
  2251. }
  2252. /**
  2253. * Cancels any ongoing request to auto-slide.
  2254. */
  2255. function cancelAutoSlide() {
  2256. clearTimeout( autoSlideTimeout );
  2257. autoSlideTimeout = -1;
  2258. }
  2259. function pauseAutoSlide() {
  2260. if( autoSlide && !autoSlidePaused ) {
  2261. autoSlidePaused = true;
  2262. dispatchEvent( 'autoslidepaused' );
  2263. clearTimeout( autoSlideTimeout );
  2264. if( autoSlidePlayer ) {
  2265. autoSlidePlayer.setPlaying( false );
  2266. }
  2267. }
  2268. }
  2269. function resumeAutoSlide() {
  2270. if( autoSlide && autoSlidePaused ) {
  2271. autoSlidePaused = false;
  2272. dispatchEvent( 'autoslideresumed' );
  2273. cueAutoSlide();
  2274. }
  2275. }
  2276. function navigateLeft() {
  2277. // Reverse for RTL
  2278. if( config.rtl ) {
  2279. if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
  2280. slide( indexh + 1 );
  2281. }
  2282. }
  2283. // Normal navigation
  2284. else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
  2285. slide( indexh - 1 );
  2286. }
  2287. }
  2288. function navigateRight() {
  2289. // Reverse for RTL
  2290. if( config.rtl ) {
  2291. if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
  2292. slide( indexh - 1 );
  2293. }
  2294. }
  2295. // Normal navigation
  2296. else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
  2297. slide( indexh + 1 );
  2298. }
  2299. }
  2300. function navigateUp() {
  2301. // Prioritize hiding fragments
  2302. if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
  2303. slide( indexh, indexv - 1 );
  2304. }
  2305. }
  2306. function navigateDown() {
  2307. // Prioritize revealing fragments
  2308. if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
  2309. slide( indexh, indexv + 1 );
  2310. }
  2311. }
  2312. /**
  2313. * Navigates backwards, prioritized in the following order:
  2314. * 1) Previous fragment
  2315. * 2) Previous vertical slide
  2316. * 3) Previous horizontal slide
  2317. */
  2318. function navigatePrev() {
  2319. // Prioritize revealing fragments
  2320. if( previousFragment() === false ) {
  2321. if( availableRoutes().up ) {
  2322. navigateUp();
  2323. }
  2324. else {
  2325. // Fetch the previous horizontal slide, if there is one
  2326. var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
  2327. if( previousSlide ) {
  2328. var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
  2329. var h = indexh - 1;
  2330. slide( h, v );
  2331. }
  2332. }
  2333. }
  2334. }
  2335. /**
  2336. * Same as #navigatePrev() but navigates forwards.
  2337. */
  2338. function navigateNext() {
  2339. // Prioritize revealing fragments
  2340. if( nextFragment() === false ) {
  2341. availableRoutes().down ? navigateDown() : navigateRight();
  2342. }
  2343. // If auto-sliding is enabled we need to cue up
  2344. // another timeout
  2345. cueAutoSlide();
  2346. }
  2347. // --------------------------------------------------------------------//
  2348. // ----------------------------- EVENTS -------------------------------//
  2349. // --------------------------------------------------------------------//
  2350. /**
  2351. * Called by all event handlers that are based on user
  2352. * input.
  2353. */
  2354. function onUserInput( event ) {
  2355. if( config.autoSlideStoppable ) {
  2356. pauseAutoSlide();
  2357. }
  2358. }
  2359. /**
  2360. * Handler for the document level 'keydown' event.
  2361. */
  2362. function onDocumentKeyDown( event ) {
  2363. // If there's a condition specified and it returns false,
  2364. // ignore this event
  2365. if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) {
  2366. return true;
  2367. }
  2368. // Remember if auto-sliding was paused so we can toggle it
  2369. var autoSlideWasPaused = autoSlidePaused;
  2370. onUserInput( event );
  2371. // Check if there's a focused element that could be using
  2372. // the keyboard
  2373. var activeElement = document.activeElement;
  2374. var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
  2375. // Disregard the event if there's a focused element or a
  2376. // keyboard modifier key is present
  2377. if( hasFocus || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
  2378. // While paused only allow "unpausing" keyboard events (b and .)
  2379. if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
  2380. return false;
  2381. }
  2382. var triggered = false;
  2383. // 1. User defined key bindings
  2384. if( typeof config.keyboard === 'object' ) {
  2385. for( var key in config.keyboard ) {
  2386. // Check if this binding matches the pressed key
  2387. if( parseInt( key, 10 ) === event.keyCode ) {
  2388. var value = config.keyboard[ key ];
  2389. // Callback function
  2390. if( typeof value === 'function' ) {
  2391. value.apply( null, [ event ] );
  2392. }
  2393. // String shortcuts to reveal.js API
  2394. else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
  2395. Reveal[ value ].call();
  2396. }
  2397. triggered = true;
  2398. }
  2399. }
  2400. }
  2401. // 2. System defined key bindings
  2402. if( triggered === false ) {
  2403. // Assume true and try to prove false
  2404. triggered = true;
  2405. switch( event.keyCode ) {
  2406. // p, page up
  2407. case 80: case 33: navigatePrev(); break;
  2408. // n, page down
  2409. case 78: case 34: navigateNext(); break;
  2410. // h, left
  2411. case 72: case 37: navigateLeft(); break;
  2412. // l, right
  2413. case 76: case 39: navigateRight(); break;
  2414. // k, up
  2415. case 75: case 38: navigateUp(); break;
  2416. // j, down
  2417. case 74: case 40: navigateDown(); break;
  2418. // home
  2419. case 36: slide( 0 ); break;
  2420. // end
  2421. case 35: slide( Number.MAX_VALUE ); break;
  2422. // space
  2423. case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
  2424. // return
  2425. case 13: isOverview() ? deactivateOverview() : triggered = false; break;
  2426. // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
  2427. case 58: case 59: case 66: case 190: case 191: togglePause(); break;
  2428. // f
  2429. case 70: enterFullscreen(); break;
  2430. // a
  2431. case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
  2432. default:
  2433. triggered = false;
  2434. }
  2435. }
  2436. // If the input resulted in a triggered action we should prevent
  2437. // the browsers default behavior
  2438. if( triggered ) {
  2439. event.preventDefault();
  2440. }
  2441. // ESC or O key
  2442. else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
  2443. if( dom.preview ) {
  2444. closePreview();
  2445. }
  2446. else {
  2447. toggleOverview();
  2448. }
  2449. event.preventDefault();
  2450. }
  2451. // If auto-sliding is enabled we need to cue up
  2452. // another timeout
  2453. cueAutoSlide();
  2454. }
  2455. /**
  2456. * Handler for the 'touchstart' event, enables support for
  2457. * swipe and pinch gestures.
  2458. */
  2459. function onTouchStart( event ) {
  2460. touch.startX = event.touches[0].clientX;
  2461. touch.startY = event.touches[0].clientY;
  2462. touch.startCount = event.touches.length;
  2463. // If there's two touches we need to memorize the distance
  2464. // between those two points to detect pinching
  2465. if( event.touches.length === 2 && config.overview ) {
  2466. touch.startSpan = distanceBetween( {
  2467. x: event.touches[1].clientX,
  2468. y: event.touches[1].clientY
  2469. }, {
  2470. x: touch.startX,
  2471. y: touch.startY
  2472. } );
  2473. }
  2474. }
  2475. /**
  2476. * Handler for the 'touchmove' event.
  2477. */
  2478. function onTouchMove( event ) {
  2479. // Each touch should only trigger one action
  2480. if( !touch.captured ) {
  2481. onUserInput( event );
  2482. var currentX = event.touches[0].clientX;
  2483. var currentY = event.touches[0].clientY;
  2484. // If the touch started with two points and still has
  2485. // two active touches; test for the pinch gesture
  2486. if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
  2487. // The current distance in pixels between the two touch points
  2488. var currentSpan = distanceBetween( {
  2489. x: event.touches[1].clientX,
  2490. y: event.touches[1].clientY
  2491. }, {
  2492. x: touch.startX,
  2493. y: touch.startY
  2494. } );
  2495. // If the span is larger than the desire amount we've got
  2496. // ourselves a pinch
  2497. if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
  2498. touch.captured = true;
  2499. if( currentSpan < touch.startSpan ) {
  2500. activateOverview();
  2501. }
  2502. else {
  2503. deactivateOverview();
  2504. }
  2505. }
  2506. event.preventDefault();
  2507. }
  2508. // There was only one touch point, look for a swipe
  2509. else if( event.touches.length === 1 && touch.startCount !== 2 ) {
  2510. var deltaX = currentX - touch.startX,
  2511. deltaY = currentY - touch.startY;
  2512. if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  2513. touch.captured = true;
  2514. navigateLeft();
  2515. }
  2516. else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  2517. touch.captured = true;
  2518. navigateRight();
  2519. }
  2520. else if( deltaY > touch.threshold ) {
  2521. touch.captured = true;
  2522. navigateUp();
  2523. }
  2524. else if( deltaY < -touch.threshold ) {
  2525. touch.captured = true;
  2526. navigateDown();
  2527. }
  2528. // If we're embedded, only block touch events if they have
  2529. // triggered an action
  2530. if( config.embedded ) {
  2531. if( touch.captured || isVerticalSlide( currentSlide ) ) {
  2532. event.preventDefault();
  2533. }
  2534. }
  2535. // Not embedded? Block them all to avoid needless tossing
  2536. // around of the viewport in iOS
  2537. else {
  2538. event.preventDefault();
  2539. }
  2540. }
  2541. }
  2542. // There's a bug with swiping on some Android devices unless
  2543. // the default action is always prevented
  2544. else if( navigator.userAgent.match( /android/gi ) ) {
  2545. event.preventDefault();
  2546. }
  2547. }
  2548. /**
  2549. * Handler for the 'touchend' event.
  2550. */
  2551. function onTouchEnd( event ) {
  2552. touch.captured = false;
  2553. }
  2554. /**
  2555. * Convert pointer down to touch start.
  2556. */
  2557. function onPointerDown( event ) {
  2558. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
  2559. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2560. onTouchStart( event );
  2561. }
  2562. }
  2563. /**
  2564. * Convert pointer move to touch move.
  2565. */
  2566. function onPointerMove( event ) {
  2567. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
  2568. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2569. onTouchMove( event );
  2570. }
  2571. }
  2572. /**
  2573. * Convert pointer up to touch end.
  2574. */
  2575. function onPointerUp( event ) {
  2576. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
  2577. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2578. onTouchEnd( event );
  2579. }
  2580. }
  2581. /**
  2582. * Handles mouse wheel scrolling, throttled to avoid skipping
  2583. * multiple slides.
  2584. */
  2585. function onDocumentMouseScroll( event ) {
  2586. if( Date.now() - lastMouseWheelStep > 600 ) {
  2587. lastMouseWheelStep = Date.now();
  2588. var delta = event.detail || -event.wheelDelta;
  2589. if( delta > 0 ) {
  2590. navigateNext();
  2591. }
  2592. else {
  2593. navigatePrev();
  2594. }
  2595. }
  2596. }
  2597. /**
  2598. * Clicking on the progress bar results in a navigation to the
  2599. * closest approximate horizontal slide using this equation:
  2600. *
  2601. * ( clickX / presentationWidth ) * numberOfSlides
  2602. */
  2603. function onProgressClicked( event ) {
  2604. onUserInput( event );
  2605. event.preventDefault();
  2606. var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
  2607. var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
  2608. slide( slideIndex );
  2609. }
  2610. /**
  2611. * Event handler for navigation control buttons.
  2612. */
  2613. function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
  2614. function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
  2615. function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
  2616. function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
  2617. function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
  2618. function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
  2619. /**
  2620. * Handler for the window level 'hashchange' event.
  2621. */
  2622. function onWindowHashChange( event ) {
  2623. readURL();
  2624. }
  2625. /**
  2626. * Handler for the window level 'resize' event.
  2627. */
  2628. function onWindowResize( event ) {
  2629. layout();
  2630. }
  2631. /**
  2632. * Handle for the window level 'visibilitychange' event.
  2633. */
  2634. function onPageVisibilityChange( event ) {
  2635. var isHidden = document.webkitHidden ||
  2636. document.msHidden ||
  2637. document.hidden;
  2638. // If, after clicking a link or similar and we're coming back,
  2639. // focus the document.body to ensure we can use keyboard shortcuts
  2640. if( isHidden === false && document.activeElement !== document.body ) {
  2641. document.activeElement.blur();
  2642. document.body.focus();
  2643. }
  2644. }
  2645. /**
  2646. * Invoked when a slide is and we're in the overview.
  2647. */
  2648. function onOverviewSlideClicked( event ) {
  2649. // TODO There's a bug here where the event listeners are not
  2650. // removed after deactivating the overview.
  2651. if( eventsAreBound && isOverview() ) {
  2652. event.preventDefault();
  2653. var element = event.target;
  2654. while( element && !element.nodeName.match( /section/gi ) ) {
  2655. element = element.parentNode;
  2656. }
  2657. if( element && !element.classList.contains( 'disabled' ) ) {
  2658. deactivateOverview();
  2659. if( element.nodeName.match( /section/gi ) ) {
  2660. var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
  2661. v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
  2662. slide( h, v );
  2663. }
  2664. }
  2665. }
  2666. }
  2667. /**
  2668. * Handles clicks on links that are set to preview in the
  2669. * iframe overlay.
  2670. */
  2671. function onPreviewLinkClicked( event ) {
  2672. var url = event.target.getAttribute( 'href' );
  2673. if( url ) {
  2674. openPreview( url );
  2675. event.preventDefault();
  2676. }
  2677. }
  2678. /**
  2679. * Handles click on the auto-sliding controls element.
  2680. */
  2681. function onAutoSlidePlayerClick( event ) {
  2682. // Replay
  2683. if( Reveal.isLastSlide() && config.loop === false ) {
  2684. slide( 0, 0 );
  2685. resumeAutoSlide();
  2686. }
  2687. // Resume
  2688. else if( autoSlidePaused ) {
  2689. resumeAutoSlide();
  2690. }
  2691. // Pause
  2692. else {
  2693. pauseAutoSlide();
  2694. }
  2695. }
  2696. // --------------------------------------------------------------------//
  2697. // ------------------------ PLAYBACK COMPONENT ------------------------//
  2698. // --------------------------------------------------------------------//
  2699. /**
  2700. * Constructor for the playback component, which displays
  2701. * play/pause/progress controls.
  2702. *
  2703. * @param {HTMLElement} container The component will append
  2704. * itself to this
  2705. * @param {Function} progressCheck A method which will be
  2706. * called frequently to get the current progress on a range
  2707. * of 0-1
  2708. */
  2709. function Playback( container, progressCheck ) {
  2710. // Cosmetics
  2711. this.diameter = 50;
  2712. this.thickness = 3;
  2713. // Flags if we are currently playing
  2714. this.playing = false;
  2715. // Current progress on a 0-1 range
  2716. this.progress = 0;
  2717. // Used to loop the animation smoothly
  2718. this.progressOffset = 1;
  2719. this.container = container;
  2720. this.progressCheck = progressCheck;
  2721. this.canvas = document.createElement( 'canvas' );
  2722. this.canvas.className = 'playback';
  2723. this.canvas.width = this.diameter;
  2724. this.canvas.height = this.diameter;
  2725. this.context = this.canvas.getContext( '2d' );
  2726. this.container.appendChild( this.canvas );
  2727. this.render();
  2728. }
  2729. Playback.prototype.setPlaying = function( value ) {
  2730. var wasPlaying = this.playing;
  2731. this.playing = value;
  2732. // Start repainting if we weren't already
  2733. if( !wasPlaying && this.playing ) {
  2734. this.animate();
  2735. }
  2736. else {
  2737. this.render();
  2738. }
  2739. };
  2740. Playback.prototype.animate = function() {
  2741. var progressBefore = this.progress;
  2742. this.progress = this.progressCheck();
  2743. // When we loop, offset the progress so that it eases
  2744. // smoothly rather than immediately resetting
  2745. if( progressBefore > 0.8 && this.progress < 0.2 ) {
  2746. this.progressOffset = this.progress;
  2747. }
  2748. this.render();
  2749. if( this.playing ) {
  2750. features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
  2751. }
  2752. };
  2753. /**
  2754. * Renders the current progress and playback state.
  2755. */
  2756. Playback.prototype.render = function() {
  2757. var progress = this.playing ? this.progress : 0,
  2758. radius = ( this.diameter / 2 ) - this.thickness,
  2759. x = this.diameter / 2,
  2760. y = this.diameter / 2,
  2761. iconSize = 14;
  2762. // Ease towards 1
  2763. this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
  2764. var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
  2765. var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
  2766. this.context.save();
  2767. this.context.clearRect( 0, 0, this.diameter, this.diameter );
  2768. // Solid background color
  2769. this.context.beginPath();
  2770. this.context.arc( x, y, radius + 2, 0, Math.PI * 2, false );
  2771. this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
  2772. this.context.fill();
  2773. // Draw progress track
  2774. this.context.beginPath();
  2775. this.context.arc( x, y, radius, 0, Math.PI * 2, false );
  2776. this.context.lineWidth = this.thickness;
  2777. this.context.strokeStyle = '#666';
  2778. this.context.stroke();
  2779. if( this.playing ) {
  2780. // Draw progress on top of track
  2781. this.context.beginPath();
  2782. this.context.arc( x, y, radius, startAngle, endAngle, false );
  2783. this.context.lineWidth = this.thickness;
  2784. this.context.strokeStyle = '#fff';
  2785. this.context.stroke();
  2786. }
  2787. this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
  2788. // Draw play/pause icons
  2789. if( this.playing ) {
  2790. this.context.fillStyle = '#fff';
  2791. this.context.fillRect( 0, 0, iconSize / 2 - 2, iconSize );
  2792. this.context.fillRect( iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize );
  2793. }
  2794. else {
  2795. this.context.beginPath();
  2796. this.context.translate( 2, 0 );
  2797. this.context.moveTo( 0, 0 );
  2798. this.context.lineTo( iconSize - 2, iconSize / 2 );
  2799. this.context.lineTo( 0, iconSize );
  2800. this.context.fillStyle = '#fff';
  2801. this.context.fill();
  2802. }
  2803. this.context.restore();
  2804. };
  2805. Playback.prototype.on = function( type, listener ) {
  2806. this.canvas.addEventListener( type, listener, false );
  2807. };
  2808. Playback.prototype.off = function( type, listener ) {
  2809. this.canvas.removeEventListener( type, listener, false );
  2810. };
  2811. Playback.prototype.destroy = function() {
  2812. this.playing = false;
  2813. if( this.canvas.parentNode ) {
  2814. this.container.removeChild( this.canvas );
  2815. }
  2816. };
  2817. // --------------------------------------------------------------------//
  2818. // ------------------------------- API --------------------------------//
  2819. // --------------------------------------------------------------------//
  2820. return {
  2821. initialize: initialize,
  2822. configure: configure,
  2823. sync: sync,
  2824. // Navigation methods
  2825. slide: slide,
  2826. left: navigateLeft,
  2827. right: navigateRight,
  2828. up: navigateUp,
  2829. down: navigateDown,
  2830. prev: navigatePrev,
  2831. next: navigateNext,
  2832. // Fragment methods
  2833. navigateFragment: navigateFragment,
  2834. prevFragment: previousFragment,
  2835. nextFragment: nextFragment,
  2836. // Deprecated aliases
  2837. navigateTo: slide,
  2838. navigateLeft: navigateLeft,
  2839. navigateRight: navigateRight,
  2840. navigateUp: navigateUp,
  2841. navigateDown: navigateDown,
  2842. navigatePrev: navigatePrev,
  2843. navigateNext: navigateNext,
  2844. // Forces an update in slide layout
  2845. layout: layout,
  2846. // Returns an object with the available routes as booleans (left/right/top/bottom)
  2847. availableRoutes: availableRoutes,
  2848. // Returns an object with the available fragments as booleans (prev/next)
  2849. availableFragments: availableFragments,
  2850. // Toggles the overview mode on/off
  2851. toggleOverview: toggleOverview,
  2852. // Toggles the "black screen" mode on/off
  2853. togglePause: togglePause,
  2854. // Toggles the auto slide mode on/off
  2855. toggleAutoSlide: toggleAutoSlide,
  2856. // State checks
  2857. isOverview: isOverview,
  2858. isPaused: isPaused,
  2859. isAutoSliding: isAutoSliding,
  2860. // Adds or removes all internal event listeners (such as keyboard)
  2861. addEventListeners: addEventListeners,
  2862. removeEventListeners: removeEventListeners,
  2863. // Facility for persisting and restoring the presentation state
  2864. getState: getState,
  2865. setState: setState,
  2866. // Presentation progress on range of 0-1
  2867. getProgress: getProgress,
  2868. // Returns the indices of the current, or specified, slide
  2869. getIndices: getIndices,
  2870. getTotalSlides: getTotalSlides,
  2871. // Returns the slide element at the specified index
  2872. getSlide: getSlide,
  2873. // Returns the slide background element at the specified index
  2874. getSlideBackground: getSlideBackground,
  2875. // Returns the previous slide element, may be null
  2876. getPreviousSlide: function() {
  2877. return previousSlide;
  2878. },
  2879. // Returns the current slide element
  2880. getCurrentSlide: function() {
  2881. return currentSlide;
  2882. },
  2883. // Returns the current scale of the presentation content
  2884. getScale: function() {
  2885. return scale;
  2886. },
  2887. // Returns the current configuration object
  2888. getConfig: function() {
  2889. return config;
  2890. },
  2891. // Helper method, retrieves query string as a key/value hash
  2892. getQueryHash: function() {
  2893. var query = {};
  2894. location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) {
  2895. query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
  2896. } );
  2897. // Basic deserialization
  2898. for( var i in query ) {
  2899. var value = query[ i ];
  2900. query[ i ] = deserialize( unescape( value ) );
  2901. }
  2902. return query;
  2903. },
  2904. // Returns true if we're currently on the first slide
  2905. isFirstSlide: function() {
  2906. return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
  2907. },
  2908. // Returns true if we're currently on the last slide
  2909. isLastSlide: function() {
  2910. if( currentSlide ) {
  2911. // Does this slide has next a sibling?
  2912. if( currentSlide.nextElementSibling ) return false;
  2913. // If it's vertical, does its parent have a next sibling?
  2914. if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
  2915. return true;
  2916. }
  2917. return false;
  2918. },
  2919. // Checks if reveal.js has been loaded and is ready for use
  2920. isReady: function() {
  2921. return loaded;
  2922. },
  2923. // Forward event binding to the reveal DOM element
  2924. addEventListener: function( type, listener, useCapture ) {
  2925. if( 'addEventListener' in window ) {
  2926. ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
  2927. }
  2928. },
  2929. removeEventListener: function( type, listener, useCapture ) {
  2930. if( 'addEventListener' in window ) {
  2931. ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
  2932. }
  2933. },
  2934. // Programatically triggers a keyboard event
  2935. triggerKey: function( keyCode ) {
  2936. onDocumentKeyDown( { keyCode: keyCode } );
  2937. }
  2938. };
  2939. })();