reveal.js 110 KB

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