files/reveal.js/js/reveal.js in reveal-ck-3.6.0 vs files/reveal.js/js/reveal.js in reveal-ck-3.7.0
- old
+ new
@@ -1,11 +1,11 @@
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
- * Copyright (C) 2015 Hakim El Hattab, http://hakim.se
+ * Copyright (C) 2017 Hakim El Hattab, http://hakim.se
*/
(function( root, factory ) {
if( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define( function() {
@@ -23,39 +23,46 @@
'use strict';
var Reveal;
+ // The reveal.js version
+ var VERSION = '3.5.0';
+
var SLIDES_SELECTOR = '.slides section',
HORIZONTAL_SLIDES_SELECTOR = '.slides>section',
VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section',
HOME_SLIDE_SELECTOR = '.slides>section:first-of-type',
+ UA = navigator.userAgent,
- // Configurations defaults, can be overridden at initialization time
+ // Configuration defaults, can be overridden at initialization time
config = {
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions
width: 960,
height: 700,
// Factor of the display size that should remain empty around the content
- margin: 0.1,
+ margin: 0.04,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
- maxScale: 1.5,
+ maxScale: 2.0,
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
+ // Determine which displays to show the slide number on
+ showSlideNumber: 'all',
+
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
@@ -76,32 +83,47 @@
loop: false,
// Change the presentation direction to be RTL
rtl: false,
+ // Randomizes the order of slides each time the presentation loads
+ shuffle: false,
+
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
- // Flags if we should show a help overlay when the questionmark
+ // Flags if we should show a help overlay when the question-mark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
+ // Flags if speaker notes should be visible to all viewers
+ showNotes: false,
+
+ // Global override for autolaying embedded media (video/audio/iframe)
+ // - null: Media will only autoplay if data-autoplay is present
+ // - true: All media will autoplay, regardless of individual setting
+ // - false: No media will autoplay, regardless of individual setting
+ autoPlayMedia: null,
+
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
+ // Use this method for navigation when auto-sliding (defaults to navigateNext)
+ autoSlideMethod: null,
+
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Apply a 3D roll to links on hover
rollingLinks: false,
@@ -116,11 +138,11 @@
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false,
- // Focuses body when page changes visiblity to ensure keyboard shortcuts work
+ // Focuses body when page changes visibility to ensure keyboard shortcuts work
focusBodyOnPageVisibilityChange: true,
// Transition style
transition: 'slide', // none/fade/slide/convex/concave/zoom
@@ -134,21 +156,49 @@
parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
+ // Amount of pixels to move the parallax background per slide step
+ parallaxBackgroundHorizontal: null,
+ parallaxBackgroundVertical: null,
+
+ // The maximum number of pages a single slide can expand onto when printing
+ // to PDF, unlimited by default
+ pdfMaxPagesPerSlide: Number.POSITIVE_INFINITY,
+
+ // Offset used to reduce the height of content within exported PDF pages.
+ // This exists to account for environment differences based on how you
+ // print to PDF. CLI printing options, like phantomjs and wkpdf, can end
+ // on precisely the total height of the document whereas in-browser
+ // printing has to end one pixel before.
+ pdfPageHeightOffset: -1,
+
// Number of slides away from the current that are visible
viewDistance: 3,
+ // The display mode that will be used to show slides
+ display: 'block',
+
// Script dependencies to load
dependencies: []
},
+ // Flags if Reveal.initialize() has been called
+ initialized = false,
+
// Flags if reveal.js is loaded (has dispatched the 'ready' event)
loaded = false,
+ // Flags if the overview mode is currently active
+ overview = false,
+
+ // Holds the dimensions of our overview slides, including margins
+ overviewSlideWidth = null,
+ overviewSlideHeight = null,
+
// The horizontal and vertical index of the currently active slide
indexh,
indexv,
// The previous and current slide HTML elements
@@ -163,19 +213,26 @@
state = [],
// The current scale of the presentation (see width/height config)
scale = 1,
+ // CSS transform that is currently applied to the slides container,
+ // split into two groups
+ slidesTransform = { layout: '', overview: '' },
+
// Cached references to DOM elements
dom = {},
// Features supported by the browser, see #checkCapabilities()
features = {},
// Client is a mobile device, see #checkCapabilities()
isMobileDevice,
+ // Client is a desktop Chrome, see #checkCapabilities()
+ isChrome,
+
// Throttles mouse wheel navigation
lastMouseWheelStep = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
@@ -220,23 +277,32 @@
/**
* Starts up the presentation if the client is capable.
*/
function initialize( options ) {
+ // Make sure we only initialize once
+ if( initialized === true ) return;
+
+ initialized = true;
+
checkCapabilities();
if( !features.transforms2d && !features.transforms3d ) {
document.body.setAttribute( 'class', 'no-transforms' );
- // Since JS won't be running any further, we need to load all
- // images that were intended to lazy load now
- var images = document.getElementsByTagName( 'img' );
- for( var i = 0, len = images.length; i < len; i++ ) {
- var image = images[i];
- if( image.getAttribute( 'data-src' ) ) {
- image.setAttribute( 'src', image.getAttribute( 'data-src' ) );
- image.removeAttribute( 'data-src' );
+ // Since JS won't be running any further, we load all lazy
+ // loading elements upfront
+ var images = toArray( document.getElementsByTagName( 'img' ) ),
+ iframes = toArray( document.getElementsByTagName( 'iframe' ) );
+
+ var lazyLoadable = images.concat( iframes );
+
+ for( var i = 0, len = lazyLoadable.length; i < len; i++ ) {
+ var element = lazyLoadable[i];
+ if( element.getAttribute( 'data-src' ) ) {
+ element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
+ element.removeAttribute( 'data-src' );
}
}
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
@@ -272,30 +338,41 @@
* Inspect the client to see what it's capable of, this
* should only happens once per runtime.
*/
function checkCapabilities() {
- features.transforms3d = 'WebkitPerspective' in document.body.style ||
- 'MozPerspective' in document.body.style ||
- 'msPerspective' in document.body.style ||
- 'OPerspective' in document.body.style ||
- 'perspective' in document.body.style;
+ isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA );
+ isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA );
- features.transforms2d = 'WebkitTransform' in document.body.style ||
- 'MozTransform' in document.body.style ||
- 'msTransform' in document.body.style ||
- 'OTransform' in document.body.style ||
- 'transform' in document.body.style;
+ var testElement = document.createElement( 'div' );
+ features.transforms3d = 'WebkitPerspective' in testElement.style ||
+ 'MozPerspective' in testElement.style ||
+ 'msPerspective' in testElement.style ||
+ 'OPerspective' in testElement.style ||
+ 'perspective' in testElement.style;
+
+ features.transforms2d = 'WebkitTransform' in testElement.style ||
+ 'MozTransform' in testElement.style ||
+ 'msTransform' in testElement.style ||
+ 'OTransform' in testElement.style ||
+ 'transform' in testElement.style;
+
features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
features.canvas = !!document.createElement( 'canvas' ).getContext;
- features.touch = !!( 'ontouchstart' in window );
+ // Transitions in the overview are disabled in desktop and
+ // Safari due to lag
+ features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA );
- isMobileDevice = navigator.userAgent.match( /(iphone|ipod|ipad|android)/gi );
+ // Flags if we should use zoom instead of transform to scale
+ // up slides. Zoom produces crisper results but has a lot of
+ // xbrowser quirks so we only use it in whitelsited browsers.
+ features.zoom = 'zoom' in testElement.style && !isMobileDevice &&
+ ( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) );
}
/**
* Loads the dependencies of reveal.js. Dependencies are
@@ -371,10 +448,13 @@
setupDOM();
// Listen to messages posted to this window
setupPostMessage();
+ // Prevent the slides from being scrolled out of view
+ setupScrollPrevention();
+
// Resets all vertical slides so that only the first is visible
resetVerticalSlides();
// Updates the presentation to match the current configuration values
configure();
@@ -391,10 +471,12 @@
// Enable transitions now that we're loaded
dom.slides.classList.remove( 'no-transition' );
loaded = true;
+ dom.wrapper.classList.add( 'ready' );
+
dispatchEvent( 'ready', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
@@ -433,24 +515,28 @@
dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' );
dom.progressbar = dom.progress.querySelector( 'span' );
// Arrow controls
createSingletonNode( dom.wrapper, 'aside', 'controls',
- '<div class="navigate-left"></div>' +
- '<div class="navigate-right"></div>' +
- '<div class="navigate-up"></div>' +
- '<div class="navigate-down"></div>' );
+ '<button class="navigate-left" aria-label="previous slide"></button>' +
+ '<button class="navigate-right" aria-label="next slide"></button>' +
+ '<button class="navigate-up" aria-label="above slide"></button>' +
+ '<button class="navigate-down" aria-label="below slide"></button>' );
// Slide number
dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' );
+ // Element containing notes that are visible to the audience
+ dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null );
+ dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' );
+ dom.speakerNotes.setAttribute( 'tabindex', '0' );
+
// Overlay graphic which is displayed during the paused mode
createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null );
// Cache references to elements
dom.controls = document.querySelector( '.reveal .controls' );
- dom.theme = document.querySelector( '#theme' );
dom.wrapper.setAttribute( 'role', 'application' );
// There can be multiple instances of controls throughout the page
dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
@@ -465,20 +551,22 @@
/**
* Creates a hidden div with role aria-live to announce the
* current slide content. Hide the div off-screen to make it
* available only to Assistive Technologies.
+ *
+ * @return {HTMLElement}
*/
function createStatusDiv() {
var statusDiv = document.getElementById( 'aria-status-div' );
if( !statusDiv ) {
statusDiv = document.createElement( 'div' );
statusDiv.style.position = 'absolute';
statusDiv.style.height = '1px';
statusDiv.style.width = '1px';
- statusDiv.style.overflow ='hidden';
+ statusDiv.style.overflow = 'hidden';
statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )';
statusDiv.setAttribute( 'id', 'aria-status-div' );
statusDiv.setAttribute( 'aria-live', 'polite' );
statusDiv.setAttribute( 'aria-atomic','true' );
dom.wrapper.appendChild( statusDiv );
@@ -486,82 +574,206 @@
return statusDiv;
}
/**
+ * Converts the given HTML element into a string of text
+ * that can be announced to a screen reader. Hidden
+ * elements are excluded.
+ */
+ function getStatusText( node ) {
+
+ var text = '';
+
+ // Text node
+ if( node.nodeType === 3 ) {
+ text += node.textContent;
+ }
+ // Element node
+ else if( node.nodeType === 1 ) {
+
+ var isAriaHidden = node.getAttribute( 'aria-hidden' );
+ var isDisplayHidden = window.getComputedStyle( node )['display'] === 'none';
+ if( isAriaHidden !== 'true' && !isDisplayHidden ) {
+
+ toArray( node.childNodes ).forEach( function( child ) {
+ text += getStatusText( child );
+ } );
+
+ }
+
+ }
+
+ return text;
+
+ }
+
+ /**
* Configures the presentation for printing to a static
* PDF.
*/
function setupPDF() {
var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight );
// Dimensions of the PDF pages
var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ),
- pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
+ pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
// Dimensions of slides within the pages
var slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
- injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' );
+ injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0px;}' );
// Limit the size of certain elements to the dimensions of the slide
injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' );
document.body.classList.add( 'print-pdf' );
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
+ // Make sure stretch elements fit on slide
+ layoutSlideContents( slideWidth, slideHeight );
+
+ // Add each slide's index as attributes on itself, we need these
+ // indices to generate slide numbers below
+ toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
+ hslide.setAttribute( 'data-index-h', h );
+
+ if( hslide.classList.contains( 'stack' ) ) {
+ toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
+ vslide.setAttribute( 'data-index-h', h );
+ vslide.setAttribute( 'data-index-v', v );
+ } );
+ }
+ } );
+
// Slide and slide background layout
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) === false ) {
// Center the slide inside of the page, giving the slide some margin
var left = ( pageWidth - slideWidth ) / 2,
top = ( pageHeight - slideHeight ) / 2;
- var contentHeight = getAbsoluteHeight( slide );
+ var contentHeight = slide.scrollHeight;
var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 );
+ // Adhere to configured pages per slide limit
+ numberOfPages = Math.min( numberOfPages, config.pdfMaxPagesPerSlide );
+
// Center slides vertically
if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) {
top = Math.max( ( pageHeight - contentHeight ) / 2, 0 );
}
+ // Wrap the slide in a page element and hide its overflow
+ // so that no page ever flows onto another
+ var page = document.createElement( 'div' );
+ page.className = 'pdf-page';
+ page.style.height = ( ( pageHeight + config.pdfPageHeightOffset ) * numberOfPages ) + 'px';
+ slide.parentNode.insertBefore( page, slide );
+ page.appendChild( slide );
+
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
- // TODO Backgrounds need to be multiplied when the slide
- // stretches over multiple pages
- var background = slide.querySelector( '.slide-background' );
- if( background ) {
- background.style.width = pageWidth + 'px';
- background.style.height = ( pageHeight * numberOfPages ) + 'px';
- background.style.top = -top + 'px';
- background.style.left = -left + 'px';
+ if( slide.slideBackgroundElement ) {
+ page.insertBefore( slide.slideBackgroundElement, slide );
}
+
+ // Inject notes if `showNotes` is enabled
+ if( config.showNotes ) {
+
+ // Are there notes for this slide?
+ var notes = getSlideNotes( slide );
+ if( notes ) {
+
+ var notesSpacing = 8;
+ var notesLayout = typeof config.showNotes === 'string' ? config.showNotes : 'inline';
+ var notesElement = document.createElement( 'div' );
+ notesElement.classList.add( 'speaker-notes' );
+ notesElement.classList.add( 'speaker-notes-pdf' );
+ notesElement.setAttribute( 'data-layout', notesLayout );
+ notesElement.innerHTML = notes;
+
+ if( notesLayout === 'separate-page' ) {
+ page.parentNode.insertBefore( notesElement, page.nextSibling );
+ }
+ else {
+ notesElement.style.left = notesSpacing + 'px';
+ notesElement.style.bottom = notesSpacing + 'px';
+ notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px';
+ page.appendChild( notesElement );
+ }
+
+ }
+
+ }
+
+ // Inject slide numbers if `slideNumbers` are enabled
+ if( config.slideNumber && /all|print/i.test( config.showSlideNumber ) ) {
+ var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1,
+ slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1;
+
+ var numberElement = document.createElement( 'div' );
+ numberElement.classList.add( 'slide-number' );
+ numberElement.classList.add( 'slide-number-pdf' );
+ numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV );
+ page.appendChild( numberElement );
+ }
}
} );
// Show all fragments
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) {
fragment.classList.add( 'visible' );
} );
+ // Notify subscribers that the PDF layout is good to go
+ dispatchEvent( 'pdf-ready' );
+
}
/**
+ * This is an unfortunate necessity. Some actions – such as
+ * an input field being focused in an iframe or using the
+ * keyboard to expand text selection beyond the bounds of
+ * a slide – can trigger our content to be pushed out of view.
+ * This scrolling can not be prevented by hiding overflow in
+ * CSS (we already do) so we have to resort to repeatedly
+ * checking if the slides have been offset :(
+ */
+ function setupScrollPrevention() {
+
+ setInterval( function() {
+ if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) {
+ dom.wrapper.scrollTop = 0;
+ dom.wrapper.scrollLeft = 0;
+ }
+ }, 1000 );
+
+ }
+
+ /**
* Creates an HTML element and returns a reference to it.
* If the element already exists the existing instance will
* be returned.
+ *
+ * @param {HTMLElement} container
+ * @param {string} tagname
+ * @param {string} classname
+ * @param {string} innerHTML
+ *
+ * @return {HTMLElement}
*/
function createSingletonNode( container, tagname, classname, innerHTML ) {
// Find all nodes matching the description
var nodes = container.querySelectorAll( '.' + classname );
@@ -601,28 +813,16 @@
dom.background.classList.add( 'no-transition' );
// Iterate over all horizontal slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
- var backgroundStack;
+ var backgroundStack = createBackground( slideh, dom.background );
- if( printMode ) {
- backgroundStack = createBackground( slideh, slideh );
- }
- else {
- backgroundStack = createBackground( slideh, dom.background );
- }
-
// Iterate over all vertical slides
toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
- if( printMode ) {
- createBackground( slidev, slidev );
- }
- else {
- createBackground( slidev, backgroundStack );
- }
+ createBackground( slidev, backgroundStack );
backgroundStack.classList.add( 'stack' );
} );
@@ -656,10 +856,11 @@
* Creates a background for the given slide.
*
* @param {HTMLElement} slide
* @param {HTMLElement} container The element that the background
* should be appended to
+ * @return {HTMLElement} New background div
*/
function createBackground( slide, container ) {
var data = {
background: slide.getAttribute( 'data-background' ),
@@ -678,11 +879,11 @@
// Carry over custom classes from the slide to the background
element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' );
if( data.background ) {
// Auto-wrap image urls in url(...)
- if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) {
+ if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)([?#]|$)/gi.test( data.background ) ) {
slide.setAttribute( 'data-background-image', data.background );
}
else {
element.style.background = data.background;
}
@@ -703,10 +904,11 @@
data.backgroundTransition );
}
// Additional and optional background properties
if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
+ if( data.backgroundSize ) element.setAttribute( 'data-background-size', data.backgroundSize );
if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
@@ -714,22 +916,24 @@
// If backgrounds are being recreated, clear old classes
slide.classList.remove( 'has-dark-background' );
slide.classList.remove( 'has-light-background' );
+ slide.slideBackgroundElement = element;
+
// If this slide has a background color, add a class that
// signals if it is light or dark. If the slide has no background
// color, no class will be set
- var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor;
- if( computedBackgroundColor ) {
- var rgb = colorToRgb( computedBackgroundColor );
+ var computedBackgroundStyle = window.getComputedStyle( element );
+ if( computedBackgroundStyle && computedBackgroundStyle.backgroundColor ) {
+ var rgb = colorToRgb( computedBackgroundStyle.backgroundColor );
// Ignore fully transparent backgrounds. Some browsers return
// rgba(0,0,0,0) when reading the computed background color of
// an element with no background
if( rgb && rgb.a !== 0 ) {
- if( colorBrightness( computedBackgroundColor ) < 128 ) {
+ if( colorBrightness( computedBackgroundStyle.backgroundColor ) < 128 ) {
slide.classList.add( 'has-dark-background' );
}
else {
slide.classList.add( 'has-light-background' );
}
@@ -755,11 +959,11 @@
if( config.postMessage ) {
window.addEventListener( 'message', function ( event ) {
var data = event.data;
// Make sure we're dealing with JSON
- if( data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
+ if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
data = JSON.parse( data );
// Check if the requested method can be found
if( data.method && typeof Reveal[data.method] === 'function' ) {
Reveal[data.method].apply( Reveal, data.args );
@@ -771,10 +975,12 @@
}
/**
* Applies the configuration settings from the config
* object. May be called multiple times.
+ *
+ * @param {object} options
*/
function configure( options ) {
var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length;
@@ -793,10 +999,14 @@
dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
dom.controls.style.display = config.controls ? 'block' : 'none';
dom.progress.style.display = config.progress ? 'block' : 'none';
+ if( config.shuffle ) {
+ shuffle();
+ }
+
if( config.rtl ) {
dom.wrapper.classList.add( 'rtl' );
}
else {
dom.wrapper.classList.remove( 'rtl' );
@@ -812,10 +1022,18 @@
// Exit the paused mode if it was configured off
if( config.pause === false ) {
resume();
}
+ if( config.showNotes ) {
+ dom.speakerNotes.classList.add( 'visible' );
+ dom.speakerNotes.setAttribute( 'data-layout', typeof config.showNotes === 'string' ? config.showNotes : 'inline' );
+ }
+ else {
+ dom.speakerNotes.classList.remove( 'visible' );
+ }
+
if( config.mouseWheel ) {
document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
else {
@@ -832,14 +1050,15 @@
}
// Iframe link previews
if( config.previewLinks ) {
enablePreviewLinks();
+ disablePreviewLinks( '[data-preview-link=false]' );
}
else {
disablePreviewLinks();
- enablePreviewLinks( '[data-preview-link]' );
+ enablePreviewLinks( '[data-preview-link]:not([data-preview-link=false])' );
}
// Remove existing auto-slide controls
if( autoSlidePlayer ) {
autoSlidePlayer.destroy();
@@ -862,10 +1081,23 @@
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
} );
}
+ // Slide numbers
+ var slideNumberDisplay = 'none';
+ if( config.slideNumber && !isPrintingPDF() ) {
+ if( config.showSlideNumber === 'all' ) {
+ slideNumberDisplay = 'block';
+ }
+ else if( config.showSlideNumber === 'speaker' && isSpeakerNotes() ) {
+ slideNumberDisplay = 'block';
+ }
+ }
+
+ dom.slideNumber.style.display = slideNumberDisplay;
+
sync();
}
/**
@@ -929,11 +1161,11 @@
// supports both
var pointerEvents = [ 'touchstart', 'click' ];
// Only support touch for Android, fixes double navigations in
// stock browser
- if( navigator.userAgent.match( /android/gi ) ) {
+ if( UA.match( /android/gi ) ) {
pointerEvents = [ 'touchstart' ];
}
pointerEvents.forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
@@ -991,10 +1223,13 @@
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
+ *
+ * @param {object} a
+ * @param {object} b
*/
function extend( a, b ) {
for( var i in b ) {
a[ i ] = b[ i ];
@@ -1002,39 +1237,47 @@
}
/**
* Converts the target object to an array.
+ *
+ * @param {object} o
+ * @return {object[]}
*/
function toArray( o ) {
return Array.prototype.slice.call( o );
}
/**
* Utility for deserializing a value.
+ *
+ * @param {*} value
+ * @return {*}
*/
function deserialize( value ) {
if( typeof value === 'string' ) {
if( value === 'null' ) return null;
else if( value === 'true' ) return true;
else if( value === 'false' ) return false;
- else if( value.match( /^\d+$/ ) ) return parseFloat( value );
+ else if( value.match( /^[\d\.]+$/ ) ) return parseFloat( value );
}
return value;
}
/**
* Measures the distance in pixels between point a
* and point b.
*
- * @param {Object} a point with x/y properties
- * @param {Object} b point with x/y properties
+ * @param {object} a point with x/y properties
+ * @param {object} b point with x/y properties
+ *
+ * @return {number}
*/
function distanceBetween( a, b ) {
var dx = a.x - b.x,
dy = a.y - b.y;
@@ -1043,23 +1286,50 @@
}
/**
* Applies a CSS transform to the target element.
+ *
+ * @param {HTMLElement} element
+ * @param {string} transform
*/
function transformElement( element, transform ) {
element.style.WebkitTransform = transform;
element.style.MozTransform = transform;
element.style.msTransform = transform;
- element.style.OTransform = transform;
element.style.transform = transform;
}
/**
+ * Applies CSS transforms to the slides container. The container
+ * is transformed from two separate sources: layout and the overview
+ * mode.
+ *
+ * @param {object} transforms
+ */
+ function transformSlides( transforms ) {
+
+ // Pick up new transforms from arguments
+ if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout;
+ if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview;
+
+ // Apply the transforms to the slides container
+ if( slidesTransform.layout ) {
+ transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview );
+ }
+ else {
+ transformElement( dom.slides, slidesTransform.overview );
+ }
+
+ }
+
+ /**
* Injects the given CSS styles into the DOM.
+ *
+ * @param {string} value
*/
function injectStyleSheet( value ) {
var tag = document.createElement( 'style' );
tag.type = 'text/css';
@@ -1072,18 +1342,60 @@
document.getElementsByTagName( 'head' )[0].appendChild( tag );
}
/**
- * Measures the distance in pixels between point a and point b.
+ * Find the closest parent that matches the given
+ * selector.
*
- * @param {String} color The string representation of a color,
- * the following formats are supported:
- * - #000
- * - #000000
- * - rgb(0,0,0)
+ * @param {HTMLElement} target The child element
+ * @param {String} selector The CSS selector to match
+ * the parents against
+ *
+ * @return {HTMLElement} The matched parent or null
+ * if no matching parent was found
*/
+ function closestParent( target, selector ) {
+
+ var parent = target.parentNode;
+
+ while( parent ) {
+
+ // There's some overhead doing this each time, we don't
+ // want to rewrite the element prototype but should still
+ // be enough to feature detect once at startup...
+ var matchesMethod = parent.matches || parent.matchesSelector || parent.msMatchesSelector;
+
+ // If we find a match, we're all set
+ if( matchesMethod && matchesMethod.call( parent, selector ) ) {
+ return parent;
+ }
+
+ // Keep searching
+ parent = parent.parentNode;
+
+ }
+
+ return null;
+
+ }
+
+ /**
+ * Converts various color input formats to an {r:0,g:0,b:0} object.
+ *
+ * @param {string} color The string representation of a color
+ * @example
+ * colorToRgb('#000');
+ * @example
+ * colorToRgb('#000000');
+ * @example
+ * colorToRgb('rgb(0,0,0)');
+ * @example
+ * colorToRgb('rgba(0,0,0)');
+ *
+ * @return {{r: number, g: number, b: number, [a]: number}|null}
+ */
function colorToRgb( color ) {
var hex3 = color.match( /^#([0-9a-f]{3})$/i );
if( hex3 && hex3[1] ) {
hex3 = hex3[1];
@@ -1128,11 +1440,12 @@
}
/**
* Calculates brightness on a scale of 0-255.
*
- * @param color See colorStringToRgb for supported formats.
+ * @param {string} color See colorToRgb for supported formats.
+ * @see {@link colorToRgb}
*/
function colorBrightness( color ) {
if( typeof color === 'string' ) color = colorToRgb( color );
@@ -1143,49 +1456,17 @@
return null;
}
/**
- * Retrieves the height of the given element by looking
- * at the position and height of its immediate children.
- */
- function getAbsoluteHeight( element ) {
-
- var height = 0;
-
- if( element ) {
- var absoluteChildren = 0;
-
- toArray( element.childNodes ).forEach( function( child ) {
-
- if( typeof child.offsetTop === 'number' && child.style ) {
- // Count # of abs children
- if( window.getComputedStyle( child ).position === 'absolute' ) {
- absoluteChildren += 1;
- }
-
- height = Math.max( height, child.offsetTop + child.offsetHeight );
- }
-
- } );
-
- // If there are no absolute children, use offsetHeight
- if( absoluteChildren === 0 ) {
- height = element.offsetHeight;
- }
-
- }
-
- return height;
-
- }
-
- /**
* Returns the remaining height within the parent of the
* target element.
*
* remaining height = [ configured parent height ] - [ current parent height ]
+ *
+ * @param {HTMLElement} element
+ * @param {number} [height]
*/
function getRemainingHeight( element, height ) {
height = height || 0;
@@ -1304,10 +1585,12 @@
}
/**
* Bind preview frame links.
+ *
+ * @param {string} [selector=a] - selector for anchors
*/
function enablePreviewLinks( selector ) {
var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
@@ -1320,13 +1603,13 @@
}
/**
* Unbind preview frame links.
*/
- function disablePreviewLinks() {
+ function disablePreviewLinks( selector ) {
- var anchors = toArray( document.querySelectorAll( 'a' ) );
+ var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.removeEventListener( 'click', onPreviewLinkClicked, false );
}
@@ -1334,10 +1617,12 @@
}
/**
* Opens a preview window for the target URL.
+ *
+ * @param {string} url - url for preview iframe src
*/
function showPreview( url ) {
closeOverlay();
@@ -1352,10 +1637,13 @@
'<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
'</header>',
'<div class="spinner"></div>',
'<div class="viewport">',
'<iframe src="'+ url +'"></iframe>',
+ '<small class="viewport-inner">',
+ '<span class="x-frame-error">Unable to load iframe. This is likely due to the site\'s policy (x-frame-options).</span>',
+ '</small>',
'</div>'
].join('');
dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
dom.overlay.classList.add( 'loaded' );
@@ -1375,12 +1663,34 @@
}, 1 );
}
/**
- * Opens a overlay window with help material.
+ * Open or close help overlay window.
+ *
+ * @param {Boolean} [override] Flag which overrides the
+ * toggle logic and forcibly sets the desired state. True means
+ * help is open, false means it's closed.
*/
+ function toggleHelp( override ){
+
+ if( typeof override === 'boolean' ) {
+ override ? showHelp() : closeOverlay();
+ }
+ else {
+ if( dom.overlay ) {
+ closeOverlay();
+ }
+ else {
+ showHelp();
+ }
+ }
+ }
+
+ /**
+ * Opens an overlay window with help material.
+ */
function showHelp() {
if( config.help ) {
closeOverlay();
@@ -1441,14 +1751,12 @@
if( dom.wrapper && !isPrintingPDF() ) {
var size = getComputedSlideSize();
- var slidePadding = 20; // TODO Dig this out of DOM
-
// Layout the contents of the slides
- layoutSlideContents( config.width, config.height, slidePadding );
+ layoutSlideContents( config.width, config.height );
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
@@ -1463,24 +1771,32 @@
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
- transformElement( dom.slides, '' );
+ transformSlides( { layout: '' } );
}
else {
- // Prefer zooming in desktop Chrome so that content remains crisp
- if( !isMobileDevice && /chrome/i.test( navigator.userAgent ) && typeof dom.slides.style.zoom !== 'undefined' ) {
+ // Prefer zoom for scaling up so that content remains crisp.
+ // Don't use zoom to scale down since that can lead to shifts
+ // in text layout/line breaks.
+ if( scale > 1 && features.zoom ) {
dom.slides.style.zoom = scale;
+ dom.slides.style.left = '';
+ dom.slides.style.top = '';
+ dom.slides.style.bottom = '';
+ dom.slides.style.right = '';
+ transformSlides( { layout: '' } );
}
// Apply scale transform as a fallback
else {
+ dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
- transformElement( dom.slides, 'translate(-50%, -50%) scale('+ scale +')' );
+ transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
}
}
// Select all slides, vertical and horizontal
var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) );
@@ -1498,11 +1814,11 @@
// children will be
if( slide.classList.contains( 'stack' ) ) {
slide.style.top = 0;
}
else {
- slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px';
+ slide.style.top = Math.max( ( size.height - slide.scrollHeight ) / 2, 0 ) + 'px';
}
}
else {
slide.style.top = '';
}
@@ -1510,19 +1826,26 @@
}
updateProgress();
updateParallax();
+ if( isOverview() ) {
+ updateOverview();
+ }
+
}
}
/**
* Applies layout logic to the contents of all slides in
* the presentation.
+ *
+ * @param {string|number} width
+ * @param {string|number} height
*/
- function layoutSlideContents( width, height, padding ) {
+ function layoutSlideContents( width, height ) {
// Handle sizing of elements with the 'stretch' class
toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) {
// Determine how much vertical space we can use
@@ -1550,10 +1873,13 @@
/**
* Calculates the computed pixel size of our slides. These
* values are based on the width and height configuration
* options.
+ *
+ * @param {number} [presentationWidth=dom.wrapper.offsetWidth]
+ * @param {number} [presentationHeight=dom.wrapper.offsetHeight]
*/
function getComputedSlideSize( presentationWidth, presentationHeight ) {
var size = {
// Slide size
@@ -1564,11 +1890,11 @@
presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
presentationHeight: presentationHeight || dom.wrapper.offsetHeight
};
// Reduce available space by margin
- size.presentationWidth -= ( size.presentationHeight * config.margin );
+ size.presentationWidth -= ( size.presentationWidth * config.margin );
size.presentationHeight -= ( size.presentationHeight * config.margin );
// Slide width may be a percentage of available width
if( typeof size.width === 'string' && /%$/.test( size.width ) ) {
size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth;
@@ -1587,11 +1913,11 @@
* Stores the vertical index of a stack so that the same
* vertical slide can be selected when navigating to and
* from the stack.
*
* @param {HTMLElement} stack The vertical stack element
- * @param {int} v Index to memorize
+ * @param {string|number} [v=0] Index to memorize
*/
function setPreviousVerticalIndex( stack, v ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
stack.setAttribute( 'data-previous-indexv', v || 0 );
@@ -1618,85 +1944,121 @@
return 0;
}
/**
- * Displays the overview of slides (quick nav) by
- * scaling down and arranging all slide elements.
- *
- * Experimental feature, might be dropped if perf
- * can't be improved.
+ * Displays the overview of slides (quick nav) by scaling
+ * down and arranging all slide elements.
*/
function activateOverview() {
// Only proceed if enabled in config
- if( config.overview ) {
+ if( config.overview && !isOverview() ) {
+ overview = true;
+
+ dom.wrapper.classList.add( 'overview' );
+ dom.wrapper.classList.remove( 'overview-deactivating' );
+
+ if( features.overviewTransitions ) {
+ setTimeout( function() {
+ dom.wrapper.classList.add( 'overview-animated' );
+ }, 1 );
+ }
+
// Don't auto-slide while in overview mode
cancelAutoSlide();
- var wasActive = dom.wrapper.classList.contains( 'overview' );
+ // Move the backgrounds element into the slide container to
+ // that the same scaling is applied
+ dom.slides.appendChild( dom.background );
- // Vary the depth of the overview based on screen size
- var depth = window.innerWidth < 400 ? 1000 : 2500;
+ // Clicking on an overview slide navigates to it
+ toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
+ if( !slide.classList.contains( 'stack' ) ) {
+ slide.addEventListener( 'click', onOverviewSlideClicked, true );
+ }
+ } );
- dom.wrapper.classList.add( 'overview' );
- dom.wrapper.classList.remove( 'overview-deactivating' );
+ // Calculate slide sizes
+ var margin = 70;
+ var slideSize = getComputedSlideSize();
+ overviewSlideWidth = slideSize.width + margin;
+ overviewSlideHeight = slideSize.height + margin;
- var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
+ // Reverse in RTL mode
+ if( config.rtl ) {
+ overviewSlideWidth = -overviewSlideWidth;
+ }
- for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
- var hslide = horizontalSlides[i],
- hoffset = config.rtl ? -105 : 105;
+ updateSlidesVisibility();
+ layoutOverview();
+ updateOverview();
- hslide.setAttribute( 'data-index-h', i );
+ layout();
- // Apply CSS transform
- transformElement( hslide, 'translateZ(-'+ depth +'px) translate(' + ( ( i - indexh ) * hoffset ) + '%, 0%)' );
+ // Notify observers of the overview showing
+ dispatchEvent( 'overviewshown', {
+ 'indexh': indexh,
+ 'indexv': indexv,
+ 'currentSlide': currentSlide
+ } );
- if( hslide.classList.contains( 'stack' ) ) {
+ }
- var verticalSlides = hslide.querySelectorAll( 'section' );
+ }
- for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
- var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
+ /**
+ * Uses CSS transforms to position all slides in a grid for
+ * display inside of the overview mode.
+ */
+ function layoutOverview() {
- var vslide = verticalSlides[j];
+ // Layout slides
+ toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
+ hslide.setAttribute( 'data-index-h', h );
+ transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
- vslide.setAttribute( 'data-index-h', i );
- vslide.setAttribute( 'data-index-v', j );
+ if( hslide.classList.contains( 'stack' ) ) {
- // Apply CSS transform
- transformElement( vslide, 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)' );
+ toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
+ vslide.setAttribute( 'data-index-h', h );
+ vslide.setAttribute( 'data-index-v', v );
- // Navigate to this slide on click
- vslide.addEventListener( 'click', onOverviewSlideClicked, true );
- }
+ transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
+ } );
- }
- else {
+ }
+ } );
- // Navigate to this slide on click
- hslide.addEventListener( 'click', onOverviewSlideClicked, true );
+ // Layout slide backgrounds
+ toArray( dom.background.childNodes ).forEach( function( hbackground, h ) {
+ transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
- }
- }
+ toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) {
+ transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
+ } );
+ } );
- updateSlidesVisibility();
+ }
- layout();
+ /**
+ * Moves the overview viewport to the current slides.
+ * Called each time the current slide changes.
+ */
+ function updateOverview() {
- if( !wasActive ) {
- // Notify observers of the overview showing
- dispatchEvent( 'overviewshown', {
- 'indexh': indexh,
- 'indexv': indexv,
- 'currentSlide': currentSlide
- } );
- }
+ var vmin = Math.min( window.innerWidth, window.innerHeight );
+ var scale = Math.max( vmin / 5, 150 ) / vmin;
- }
+ transformSlides( {
+ overview: [
+ 'scale('+ scale +')',
+ 'translateX('+ ( -indexh * overviewSlideWidth ) +'px)',
+ 'translateY('+ ( -indexv * overviewSlideHeight ) +'px)'
+ ].join( ' ' )
+ } );
}
/**
* Exits the slide overview and enters the currently
@@ -1705,31 +2067,45 @@
function deactivateOverview() {
// Only proceed if enabled in config
if( config.overview ) {
+ overview = false;
+
dom.wrapper.classList.remove( 'overview' );
+ dom.wrapper.classList.remove( 'overview-animated' );
// Temporarily add a class so that transitions can do different things
// depending on whether they are exiting/entering overview, or just
// moving from slide to slide
dom.wrapper.classList.add( 'overview-deactivating' );
setTimeout( function () {
dom.wrapper.classList.remove( 'overview-deactivating' );
}, 1 );
- // Select all slides
+ // Move the background element back out
+ dom.wrapper.appendChild( dom.background );
+
+ // Clean up changes made to slides
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
- // Resets all transforms to use the external styles
transformElement( slide, '' );
slide.removeEventListener( 'click', onOverviewSlideClicked, true );
} );
+ // Clean up changes made to backgrounds
+ toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) {
+ transformElement( background, '' );
+ } );
+
+ transformSlides( { overview: '' } );
+
slide( indexh, indexv );
+ layout();
+
cueAutoSlide();
// Notify observers of the overview hiding
dispatchEvent( 'overviewhidden', {
'indexh': indexh,
@@ -1741,11 +2117,11 @@
}
/**
* Toggles the slide overview mode on and off.
*
- * @param {Boolean} override Optional flag which overrides the
+ * @param {Boolean} [override] Flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* overview is open, false means it's closed.
*/
function toggleOverview( override ) {
@@ -1764,20 +2140,21 @@
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function isOverview() {
- return dom.wrapper.classList.contains( 'overview' );
+ return overview;
}
/**
* Checks if the current or specified slide is vertical
* (nested within another slide).
*
- * @param {HTMLElement} slide [optional] The slide to check
+ * @param {HTMLElement} [slide=currentSlide] The slide to check
* orientation of
+ * @return {Boolean}
*/
function isVerticalSlide( slide ) {
// Prefer slide argument, otherwise use current slide
slide = slide ? slide : currentSlide;
@@ -1792,14 +2169,14 @@
* @see http://fullscreen.spec.whatwg.org/
* @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
*/
function enterFullscreen() {
- var element = document.body;
+ var element = document.documentElement;
// Check which implementation is available
- var requestMethod = element.requestFullScreen ||
+ var requestMethod = element.requestFullscreen ||
element.webkitRequestFullscreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
@@ -1858,21 +2235,23 @@
}
/**
* Checks if we are currently in the paused mode.
+ *
+ * @return {Boolean}
*/
function isPaused() {
return dom.wrapper.classList.contains( 'paused' );
}
/**
* Toggles the auto slide mode on and off.
*
- * @param {Boolean} override Optional flag which sets the desired state.
+ * @param {Boolean} [override] Flag which sets the desired state.
* True means autoplay starts, false means it stops.
*/
function toggleAutoSlide( override ) {
@@ -1886,10 +2265,12 @@
}
/**
* Checks if the auto slide mode is currently on.
+ *
+ * @return {Boolean}
*/
function isAutoSliding() {
return !!( autoSlide && !autoSlidePaused );
@@ -1898,27 +2279,30 @@
/**
* Steps from the current point in the presentation to the
* slide which matches the specified horizontal and vertical
* indices.
*
- * @param {int} h Horizontal index of the target slide
- * @param {int} v Vertical index of the target slide
- * @param {int} f Optional index of a fragment within the
+ * @param {number} [h=indexh] Horizontal index of the target slide
+ * @param {number} [v=indexv] Vertical index of the target slide
+ * @param {number} [f] Index of a fragment within the
* target slide to activate
- * @param {int} o Optional origin for use in multimaster environments
+ * @param {number} [o] Origin for use in multimaster environments
*/
function slide( h, v, f, o ) {
// Remember where we were at before
previousSlide = currentSlide;
// Query all horizontal slides in the deck
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
+ // Abort if there are no slides
+ if( horizontalSlides.length === 0 ) return;
+
// If no vertical index is specified and the upcoming slide is a
// stack, resume at its previous vertical index
- if( v === undefined ) {
+ if( v === undefined && !isOverview() ) {
v = getPreviousVerticalIndex( horizontalSlides[ h ] );
}
// If we were on a vertical stack, remember what vertical index
// it was on so we can resume at the same position when returning
@@ -1964,13 +2348,13 @@
// Clean up the remains of the previous state
while( stateBefore.length ) {
document.documentElement.classList.remove( stateBefore.pop() );
}
- // If the overview is active, re-activate it to update positions
+ // Update the overview if it's currently active
if( isOverview() ) {
- activateOverview();
+ updateOverview();
}
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[ indexh ],
@@ -2028,17 +2412,18 @@
stopEmbeddedContent( previousSlide );
startEmbeddedContent( currentSlide );
}
// Announce the current slide contents, for screen readers
- dom.statusDiv.textContent = currentSlide.textContent;
+ dom.statusDiv.textContent = getStatusText( currentSlide );
updateControls();
updateProgress();
updateBackground();
updateParallax();
updateSlideNumber();
+ updateNotes();
// Update the URL hash
writeURL();
cueAutoSlide();
@@ -2073,16 +2458,29 @@
sortAllFragments();
updateControls();
updateProgress();
- updateBackground( true );
updateSlideNumber();
updateSlidesVisibility();
+ updateBackground( true );
+ updateNotes();
formatEmbeddedContent();
+ // Start or stop embedded content depending on global config
+ if( config.autoPlayMedia === false ) {
+ stopEmbeddedContent( currentSlide );
+ }
+ else {
+ startEmbeddedContent( currentSlide );
+ }
+
+ if( isOverview() ) {
+ layoutOverview();
+ }
+
}
/**
* Resets all vertical slides so that only the first
* is visible.
@@ -2129,19 +2527,36 @@
} );
}
/**
+ * Randomly shuffles all slides in the deck.
+ */
+ function shuffle() {
+
+ var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
+
+ slides.forEach( function( slide ) {
+
+ // Insert this slide next to another random slide. This may
+ // cause the slide to insert before itself but that's fine.
+ dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] );
+
+ } );
+
+ }
+
+ /**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
- * @param {String} selector A CSS selector that will fetch
+ * @param {string} selector A CSS selector that will fetch
* the group of slides we are working with
- * @param {Number} index The index of the slide that should be
+ * @param {number} index The index of the slide that should be
* shown
*
- * @return {Number} The index of the slide that is now shown,
+ * @return {number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides( selector, index ) {
@@ -2267,24 +2682,30 @@
// Limit view distance on weaker devices
if( isMobileDevice ) {
viewDistance = isOverview() ? 6 : 2;
}
- // Limit view distance on weaker devices
+ // All slides need to be visible when exporting to PDF
if( isPrintingPDF() ) {
viewDistance = Number.MAX_VALUE;
}
for( var x = 0; x < horizontalSlidesLength; x++ ) {
var horizontalSlide = horizontalSlides[x];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
verticalSlidesLength = verticalSlides.length;
- // Loops so that it measures 1 between the first and last slides
- distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
+ // Determine how far away this slide is from the present
+ distanceX = Math.abs( ( indexh || 0 ) - x ) || 0;
+ // If the presentation is looped, distance should measure
+ // 1 between the first and last slides
+ if( config.loop ) {
+ distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
+ }
+
// Show the horizontal slide if it's within the view distance
if( distanceX < viewDistance ) {
showSlide( horizontalSlide );
}
else {
@@ -2314,10 +2735,26 @@
}
}
/**
+ * Pick up notes from the current slide and display them
+ * to the viewer.
+ *
+ * @see {@link config.showNotes}
+ */
+ function updateNotes() {
+
+ if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) {
+
+ dom.speakerNotes.innerHTML = getSlideNotes() || '';
+
+ }
+
+ }
+
+ /**
* Updates the progress bar to reflect the current slide.
*/
function updateProgress() {
// Update progress if enabled
@@ -2329,28 +2766,74 @@
}
/**
* Updates the slide number div to reflect the current slide.
+ *
+ * The following slide number formats are available:
+ * "h.v": horizontal . vertical slide number (default)
+ * "h/v": horizontal / vertical slide number
+ * "c": flattened slide number
+ * "c/t": flattened slide number / total slides
*/
function updateSlideNumber() {
// Update slide number if enabled
- if( config.slideNumber && dom.slideNumber) {
+ if( config.slideNumber && dom.slideNumber ) {
- // Display the number of the page using 'indexh - indexv' format
- var indexString = indexh;
- if( indexv > 0 ) {
- indexString += ' - ' + indexv;
+ var value = [];
+ var format = 'h.v';
+
+ // Check if a custom number format is available
+ if( typeof config.slideNumber === 'string' ) {
+ format = config.slideNumber;
}
- dom.slideNumber.innerHTML = indexString;
+ switch( format ) {
+ case 'c':
+ value.push( getSlidePastCount() + 1 );
+ break;
+ case 'c/t':
+ value.push( getSlidePastCount() + 1, '/', getTotalSlides() );
+ break;
+ case 'h/v':
+ value.push( indexh + 1 );
+ if( isVerticalSlide() ) value.push( '/', indexv + 1 );
+ break;
+ default:
+ value.push( indexh + 1 );
+ if( isVerticalSlide() ) value.push( '.', indexv + 1 );
+ }
+
+ dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] );
}
}
/**
+ * Applies HTML formatting to a slide number before it's
+ * written to the DOM.
+ *
+ * @param {number} a Current slide
+ * @param {string} delimiter Character to separate slide numbers
+ * @param {(number|*)} b Total slides
+ * @return {string} HTML string fragment
+ */
+ function formatSlideNumber( a, delimiter, b ) {
+
+ if( typeof b === 'number' && !isNaN( b ) ) {
+ return '<span class="slide-number-a">'+ a +'</span>' +
+ '<span class="slide-number-delimiter">'+ delimiter +'</span>' +
+ '<span class="slide-number-b">'+ b +'</span>';
+ }
+ else {
+ return '<span class="slide-number-a">'+ a +'</span>';
+ }
+
+ }
+
+ /**
* Updates the state of all control/navigation arrows.
*/
function updateControls() {
var routes = availableRoutes();
@@ -2362,49 +2845,52 @@
.concat( dom.controlsDown )
.concat( dom.controlsPrev )
.concat( dom.controlsNext ).forEach( function( node ) {
node.classList.remove( 'enabled' );
node.classList.remove( 'fragmented' );
+
+ // Set 'disabled' attribute on all directions
+ node.setAttribute( 'disabled', 'disabled' );
} );
- // Add the 'enabled' class to the available routes
- if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
- if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
- if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
- if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
+ // Add the 'enabled' class to the available routes; remove 'disabled' attribute to enable buttons
+ if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
// Prev/next buttons
- if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
- if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
+ if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
// Highlight fragment directions
if( currentSlide ) {
// Always apply fragment decorator to prev/next buttons
- if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
- if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
+ if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
// Apply fragment decorators to directional buttons based on
// what slide axis they are in
if( isVerticalSlide( currentSlide ) ) {
- if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
- if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
+ if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
}
else {
- if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
- if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
+ if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
+ if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
}
}
}
/**
* Updates the background elements to reflect the current
* slide.
*
- * @param {Boolean} includeAll If true, the backgrounds of
+ * @param {boolean} includeAll If true, the backgrounds of
* all vertical slides (not just the present) will be updated.
*/
function updateBackground( includeAll ) {
var currentBackground = null;
@@ -2457,25 +2943,29 @@
} );
}
} );
- // Stop any currently playing video background
+ // Stop content inside of previous backgrounds
if( previousBackground ) {
- var previousVideo = previousBackground.querySelector( 'video' );
- if( previousVideo ) previousVideo.pause();
+ stopEmbeddedContent( previousBackground );
}
+ // Start content in the current background
if( currentBackground ) {
- // Start video playback
- var currentVideo = currentBackground.querySelector( 'video' );
- if( currentVideo ) {
- currentVideo.currentTime = 0;
- currentVideo.play();
+ startEmbeddedContent( currentBackground );
+
+ var backgroundImageURL = currentBackground.style.backgroundImage || '';
+
+ // Restart GIFs (doesn't work in Firefox)
+ if( /\.gif/i.test( backgroundImageURL ) ) {
+ currentBackground.style.backgroundImage = '';
+ window.getComputedStyle( currentBackground ).opacity;
+ currentBackground.style.backgroundImage = backgroundImageURL;
}
// Don't transition between identical backgrounds. This
// prevents unwanted flicker.
var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
@@ -2528,36 +3018,65 @@
else {
backgroundWidth = parseInt( backgroundSize[0], 10 );
backgroundHeight = parseInt( backgroundSize[1], 10 );
}
- var slideWidth = dom.background.offsetWidth;
- var horizontalSlideCount = horizontalSlides.length;
- var horizontalOffset = -( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) * indexh;
+ var slideWidth = dom.background.offsetWidth,
+ horizontalSlideCount = horizontalSlides.length,
+ horizontalOffsetMultiplier,
+ horizontalOffset;
- var slideHeight = dom.background.offsetHeight;
- var verticalSlideCount = verticalSlides.length;
- var verticalOffset = verticalSlideCount > 1 ? -( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ) * indexv : 0;
+ if( typeof config.parallaxBackgroundHorizontal === 'number' ) {
+ horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal;
+ }
+ else {
+ horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0;
+ }
- dom.background.style.backgroundPosition = horizontalOffset + 'px ' + verticalOffset + 'px';
+ horizontalOffset = horizontalOffsetMultiplier * indexh * -1;
+ var slideHeight = dom.background.offsetHeight,
+ verticalSlideCount = verticalSlides.length,
+ verticalOffsetMultiplier,
+ verticalOffset;
+
+ if( typeof config.parallaxBackgroundVertical === 'number' ) {
+ verticalOffsetMultiplier = config.parallaxBackgroundVertical;
+ }
+ else {
+ verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 );
+ }
+
+ verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv : 0;
+
+ dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
+
}
}
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
+ *
+ * @param {HTMLElement} slide Slide to show
*/
+ /**
+ * Called when the given slide is within the configured view
+ * distance. Shows the slide element and loads any content
+ * that is set to load lazily (data-src).
+ *
+ * @param {HTMLElement} slide Slide to show
+ */
function showSlide( slide ) {
// Show the slide element
- slide.style.display = 'block';
+ slide.style.display = config.display;
// Media elements with data-src attributes
- toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src], iframe[data-src]' ) ).forEach( function( element ) {
+ toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
} );
// Media elements with <source> children
@@ -2588,46 +3107,80 @@
if( background.hasAttribute( 'data-loaded' ) === false ) {
background.setAttribute( 'data-loaded', 'true' );
var backgroundImage = slide.getAttribute( 'data-background-image' ),
backgroundVideo = slide.getAttribute( 'data-background-video' ),
+ backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ),
+ backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ),
backgroundIframe = slide.getAttribute( 'data-background-iframe' );
// Images
if( backgroundImage ) {
background.style.backgroundImage = 'url('+ backgroundImage +')';
}
// Videos
else if ( backgroundVideo && !isSpeakerNotes() ) {
var video = document.createElement( 'video' );
+ if( backgroundVideoLoop ) {
+ video.setAttribute( 'loop', '' );
+ }
+
+ if( backgroundVideoMuted ) {
+ video.muted = true;
+ }
+
+ // Inline video playback works (at least in Mobile Safari) as
+ // long as the video is muted and the `playsinline` attribute is
+ // present
+ if( isMobileDevice ) {
+ video.muted = true;
+ video.autoplay = true;
+ video.setAttribute( 'playsinline', '' );
+ }
+
// Support comma separated lists of video sources
backgroundVideo.split( ',' ).forEach( function( source ) {
video.innerHTML += '<source src="'+ source +'">';
} );
background.appendChild( video );
}
// Iframes
- else if ( backgroundIframe ) {
+ else if( backgroundIframe ) {
var iframe = document.createElement( 'iframe' );
+ iframe.setAttribute( 'allowfullscreen', '' );
+ iframe.setAttribute( 'mozallowfullscreen', '' );
+ iframe.setAttribute( 'webkitallowfullscreen', '' );
+
+ // Only load autoplaying content when the slide is shown to
+ // avoid having it play in the background
+ if( /autoplay=(1|true|yes)/gi.test( backgroundIframe ) ) {
+ iframe.setAttribute( 'data-src', backgroundIframe );
+ }
+ else {
iframe.setAttribute( 'src', backgroundIframe );
- iframe.style.width = '100%';
- iframe.style.height = '100%';
- iframe.style.maxHeight = '100%';
- iframe.style.maxWidth = '100%';
+ }
+ iframe.style.width = '100%';
+ iframe.style.height = '100%';
+ iframe.style.maxHeight = '100%';
+ iframe.style.maxWidth = '100%';
+
background.appendChild( iframe );
}
}
+
}
}
/**
* Called when the given slide is moved outside of the
* configured view distance.
+ *
+ * @param {HTMLElement} slide
*/
function hideSlide( slide ) {
// Hide the slide element
slide.style.display = 'none';
@@ -2642,11 +3195,11 @@
}
/**
* Determine what available routes there are for navigation.
*
- * @return {Object} containing four booleans: left/right/up/down
+ * @return {{left: boolean, right: boolean, up: boolean, down: boolean}}
*/
function availableRoutes() {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
@@ -2671,11 +3224,11 @@
/**
* Returns an object describing the available fragment
* directions.
*
- * @return {Object} two boolean properties: prev/next
+ * @return {{prev: boolean, next: boolean}}
*/
function availableFragments() {
if( currentSlide && config.fragments ) {
var fragments = currentSlide.querySelectorAll( '.fragment' );
@@ -2695,110 +3248,224 @@
/**
* Enforces origin-specific format rules for embedded media.
*/
function formatEmbeddedContent() {
+ var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) {
+ toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) {
+ var src = el.getAttribute( sourceAttribute );
+ if( src && src.indexOf( param ) === -1 ) {
+ el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
+ }
+ });
+ };
+
// YouTube frames must include "?enablejsapi=1"
- toArray( dom.slides.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
- var src = el.getAttribute( 'src' );
- if( !/enablejsapi\=1/gi.test( src ) ) {
- el.setAttribute( 'src', src + ( !/\?/.test( src ) ? '?' : '&' ) + 'enablejsapi=1' );
- }
- });
+ _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
+ _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
// Vimeo frames must include "?api=1"
- toArray( dom.slides.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
- var src = el.getAttribute( 'src' );
- if( !/api\=1/gi.test( src ) ) {
- el.setAttribute( 'src', src + ( !/\?/.test( src ) ? '?' : '&' ) + 'api=1' );
- }
- });
+ _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
+ _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
}
/**
* Start playback of any embedded content inside of
- * the targeted slide.
+ * the given element.
+ *
+ * @param {HTMLElement} element
*/
- function startEmbeddedContent( slide ) {
+ function startEmbeddedContent( element ) {
- if( slide && !isSpeakerNotes() ) {
+ if( element && !isSpeakerNotes() ) {
+
+ // Restart GIFs
+ toArray( element.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) {
+ // Setting the same unchanged source like this was confirmed
+ // to work in Chrome, FF & Safari
+ el.setAttribute( 'src', el.getAttribute( 'src' ) );
+ } );
+
// HTML5 media elements
- toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
- if( el.hasAttribute( 'data-autoplay' ) ) {
- el.play();
+ toArray( element.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
+ if( closestParent( el, '.fragment' ) && !closestParent( el, '.fragment.visible' ) ) {
+ return;
}
+
+ // Prefer an explicit global autoplay setting
+ var autoplay = config.autoPlayMedia;
+
+ // If no global setting is available, fall back on the element's
+ // own autoplay setting
+ if( typeof autoplay !== 'boolean' ) {
+ autoplay = el.hasAttribute( 'data-autoplay' ) || !!closestParent( el, '.slide-background' );
+ }
+
+ if( autoplay && typeof el.play === 'function' ) {
+
+ if( el.readyState > 1 ) {
+ startEmbeddedMedia( { target: el } );
+ }
+ else {
+ el.removeEventListener( 'loadeddata', startEmbeddedMedia ); // remove first to avoid dupes
+ el.addEventListener( 'loadeddata', startEmbeddedMedia );
+ }
+
+ }
} );
- // iframe embeds
- toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
- el.contentWindow.postMessage( 'slide:start', '*' );
- });
+ // Normal iframes
+ toArray( element.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) {
+ if( closestParent( el, '.fragment' ) && !closestParent( el, '.fragment.visible' ) ) {
+ return;
+ }
- // YouTube embeds
- toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
- if( el.hasAttribute( 'data-autoplay' ) ) {
- el.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
+ startEmbeddedIframe( { target: el } );
+ } );
+
+ // Lazy loading iframes
+ toArray( element.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
+ if( closestParent( el, '.fragment' ) && !closestParent( el, '.fragment.visible' ) ) {
+ return;
}
- });
- // Vimeo embeds
- toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
- if( el.hasAttribute( 'data-autoplay' ) ) {
- el.contentWindow.postMessage( '{"method":"play"}', '*' );
+ if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
+ el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes
+ el.addEventListener( 'load', startEmbeddedIframe );
+ el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
}
- });
+ } );
+
}
}
/**
+ * Starts playing an embedded video/audio element after
+ * it has finished loading.
+ *
+ * @param {object} event
+ */
+ function startEmbeddedMedia( event ) {
+
+ var isAttachedToDOM = !!closestParent( event.target, 'html' ),
+ isVisible = !!closestParent( event.target, '.present' );
+
+ if( isAttachedToDOM && isVisible ) {
+ event.target.currentTime = 0;
+ event.target.play();
+ }
+
+ event.target.removeEventListener( 'loadeddata', startEmbeddedMedia );
+
+ }
+
+ /**
+ * "Starts" the content of an embedded iframe using the
+ * postMessage API.
+ *
+ * @param {object} event
+ */
+ function startEmbeddedIframe( event ) {
+
+ var iframe = event.target;
+
+ if( iframe && iframe.contentWindow ) {
+
+ var isAttachedToDOM = !!closestParent( event.target, 'html' ),
+ isVisible = !!closestParent( event.target, '.present' );
+
+ if( isAttachedToDOM && isVisible ) {
+
+ // Prefer an explicit global autoplay setting
+ var autoplay = config.autoPlayMedia;
+
+ // If no global setting is available, fall back on the element's
+ // own autoplay setting
+ if( typeof autoplay !== 'boolean' ) {
+ autoplay = iframe.hasAttribute( 'data-autoplay' ) || !!closestParent( iframe, '.slide-background' );
+ }
+
+ // YouTube postMessage API
+ if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
+ iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
+ }
+ // Vimeo postMessage API
+ else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
+ iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
+ }
+ // Generic postMessage API
+ else {
+ iframe.contentWindow.postMessage( 'slide:start', '*' );
+ }
+
+ }
+
+ }
+
+ }
+
+ /**
* Stop playback of any embedded content inside of
* the targeted slide.
+ *
+ * @param {HTMLElement} element
*/
- function stopEmbeddedContent( slide ) {
+ function stopEmbeddedContent( element ) {
- if( slide && slide.parentNode ) {
+ if( element && element.parentNode ) {
// HTML5 media elements
- toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
- if( !el.hasAttribute( 'data-ignore' ) ) {
+ toArray( element.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
+ if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
+ el.setAttribute('data-paused-by-reveal', '');
el.pause();
}
} );
- // iframe embeds
- toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
- el.contentWindow.postMessage( 'slide:stop', '*' );
+ // Generic postMessage API for non-lazy loaded iframes
+ toArray( element.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
+ if( el.contentWindow ) el.contentWindow.postMessage( 'slide:stop', '*' );
+ el.removeEventListener( 'load', startEmbeddedIframe );
});
- // YouTube embeds
- toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
- if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
+ // YouTube postMessage API
+ toArray( element.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
+ if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
}
});
- // Vimeo embeds
- toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
- if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
+ // Vimeo postMessage API
+ toArray( element.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
+ if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"method":"pause"}', '*' );
}
});
+
+ // Lazy loading iframes
+ toArray( element.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
+ // Only removing the src doesn't actually unload the frame
+ // in all browsers (Firefox) so we set it to blank first
+ el.setAttribute( 'src', 'about:blank' );
+ el.removeAttribute( 'src' );
+ } );
}
}
/**
- * Returns a value ranging from 0-1 that represents
- * how far into the presentation we have navigated.
+ * Returns the number of past slides. This can be used as a global
+ * flattened index for slides.
+ *
+ * @return {number} Past slide count
*/
- function getProgress() {
+ function getSlidePastCount() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
- // The number of past and total slides
- var totalCount = getTotalSlides();
+ // The number of past slides
var pastCount = 0;
// Step through all slides and count the past ones
mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
@@ -2826,10 +3493,26 @@
pastCount++;
}
}
+ return pastCount;
+
+ }
+
+ /**
+ * Returns a value ranging from 0-1 that represents
+ * how far into the presentation we have navigated.
+ *
+ * @return {number}
+ */
+ function getProgress() {
+
+ // The number of past and total slides
+ var totalCount = getTotalSlides();
+ var pastCount = getSlidePastCount();
+
if( currentSlide ) {
var allFragments = currentSlide.querySelectorAll( '.fragment' );
// If there are fragments in the current slide those should be
@@ -2852,10 +3535,12 @@
}
/**
* Checks if this presentation is running inside of the
* speaker notes window.
+ *
+ * @return {boolean}
*/
function isSpeakerNotes() {
return !!window.location.search.match( /receiver/gi );
@@ -2878,11 +3563,11 @@
var element;
// Ensure the named link is a valid HTML ID attribute
if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) {
// Find the slide with the specified ID
- element = document.querySelector( '#' + name );
+ element = document.getElementById( name );
}
if( element ) {
// Find the position of the named slide and navigate to it
var indices = Reveal.getIndices( element );
@@ -2907,11 +3592,11 @@
/**
* Updates the page URL (hash) to reflect the current
* state.
*
- * @param {Number} delay The time in ms to wait before
+ * @param {number} delay The time in ms to wait before
* writing the hash
*/
function writeURL( delay ) {
if( config.history ) {
@@ -2927,11 +3612,10 @@
var url = '/';
// Attempt to create a named link based on the slide's ID
var id = currentSlide.getAttribute( 'id' );
if( id ) {
- id = id.toLowerCase();
id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' );
}
// If the current slide has an ID, use that as a named link
if( typeof id === 'string' && id.length ) {
@@ -2946,20 +3630,19 @@
window.location.hash = url;
}
}
}
-
/**
- * Retrieves the h/v location of the current, or specified,
- * slide.
+ * Retrieves the h/v location and fragment of the current,
+ * or specified, slide.
*
- * @param {HTMLElement} slide If specified, the returned
+ * @param {HTMLElement} [slide] If specified, the returned
* index will be for this slide rather than the currently
* active one
*
- * @return {Object} { h: <int>, v: <int>, f: <int> }
+ * @return {{h: number, v: number, f: number}}
*/
function getIndices( slide ) {
// By default, return the current indices
var h = indexh,
@@ -3002,20 +3685,33 @@
return { h: h, v: v, f: f };
}
/**
+ * Retrieves all slides in this presentation.
+ */
+ function getSlides() {
+
+ return toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ));
+
+ }
+
+ /**
* Retrieves the total number of slides in this presentation.
+ *
+ * @return {number}
*/
function getTotalSlides() {
- return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
+ return getSlides().length;
}
/**
* Returns the slide element matching the specified index.
+ *
+ * @return {HTMLElement}
*/
function getSlide( x, y ) {
var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
@@ -3031,22 +3727,23 @@
/**
* Returns the background element for the given slide.
* All slides, even the ones with no background properties
* defined, have a background element so as long as the
* index is valid an element will be returned.
+ *
+ * @param {number} x Horizontal background index
+ * @param {number} y Vertical background index
+ * @return {(HTMLElement[]|*)}
*/
function getSlideBackground( x, y ) {
// When printing to PDF the slide backgrounds are nested
// inside of the slides
if( isPrintingPDF() ) {
var slide = getSlide( x, y );
if( slide ) {
- var background = slide.querySelector( '.slide-background' );
- if( background && background.parentNode === slide ) {
- return background;
- }
+ return slide.slideBackgroundElement;
}
return undefined;
}
@@ -3060,13 +3757,44 @@
return horizontalBackground;
}
/**
+ * Retrieves the speaker notes from a slide. Notes can be
+ * defined in two ways:
+ * 1. As a data-notes attribute on the slide <section>
+ * 2. As an <aside class="notes"> inside of the slide
+ *
+ * @param {HTMLElement} [slide=currentSlide]
+ * @return {(string|null)}
+ */
+ function getSlideNotes( slide ) {
+
+ // Default to the current slide
+ slide = slide || currentSlide;
+
+ // Notes can be specified via the data-notes attribute...
+ if( slide.hasAttribute( 'data-notes' ) ) {
+ return slide.getAttribute( 'data-notes' );
+ }
+
+ // ... or using an <aside class="notes"> element
+ var notesElement = slide.querySelector( 'aside.notes' );
+ if( notesElement ) {
+ return notesElement.innerHTML;
+ }
+
+ return null;
+
+ }
+
+ /**
* Retrieves the current state of the presentation as
* an object. This state can then be restored at any
* time.
+ *
+ * @return {{indexh: number, indexv: number, indexf: number, paused: boolean, overview: boolean}}
*/
function getState() {
var indices = getIndices();
@@ -3081,11 +3809,12 @@
}
/**
* Restores the presentation to the given state.
*
- * @param {Object} state As generated by getState()
+ * @param {object} state As generated by getState()
+ * @see {@link getState} generates the parameter `state`
*/
function setState( state ) {
if( typeof state === 'object' ) {
slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
@@ -3115,10 +3844,13 @@
* To maintain a sensible default fragment order, fragments are presumed
* to be passed in document order. This function adds a "fragment-index"
* attribute to each node if such an attribute is not already present,
* and sets that attribute to an integer value which is the position of
* the fragment within the fragments list.
+ *
+ * @param {object[]|*} fragments
+ * @return {object[]} sorted Sorted array of fragments
*/
function sortFragments( fragments ) {
fragments = toArray( fragments );
@@ -3166,16 +3898,16 @@
}
/**
* Navigate to the specified slide fragment.
*
- * @param {Number} index The index of the fragment that
+ * @param {?number} index The index of the fragment that
* should be shown, -1 means all are invisible
- * @param {Number} offset Integer offset to apply to the
+ * @param {number} offset Integer offset to apply to the
* fragment index
*
- * @return {Boolean} true if a change was made in any
+ * @return {boolean} true if a change was made in any
* fragments visibility as part of this call
*/
function navigateFragment( index, offset ) {
if( currentSlide && config.fragments ) {
@@ -3214,24 +3946,24 @@
if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
// Announce the fragments one by one to the Screen Reader
- dom.statusDiv.textContent = element.textContent;
+ dom.statusDiv.textContent = getStatusText( element );
if( i === index ) {
element.classList.add( 'current-fragment' );
+ startEmbeddedContent( element );
}
}
// Hidden fragments
else {
if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
element.classList.remove( 'visible' );
element.classList.remove( 'current-fragment' );
}
-
} );
if( fragmentsHidden.length ) {
dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
}
@@ -3254,11 +3986,11 @@
}
/**
* Navigate to the next slide fragment.
*
- * @return {Boolean} true if there was a next fragment,
+ * @return {boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
return navigateFragment( null, 1 );
@@ -3266,11 +3998,11 @@
}
/**
* Navigate to the previous slide fragment.
*
- * @return {Boolean} true if there was a previous fragment,
+ * @return {boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
return navigateFragment( null, -1 );
@@ -3284,13 +4016,17 @@
cancelAutoSlide();
if( currentSlide ) {
- var currentFragment = currentSlide.querySelector( '.current-fragment' );
+ var fragment = currentSlide.querySelector( '.current-fragment' );
- var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null;
+ // When the slide first appears there is no "current" fragment so
+ // we look for a data-autoslide timing on the first fragment
+ if( !fragment ) fragment = currentSlide.querySelector( '.fragment' );
+
+ var fragmentAutoSlide = fragment ? fragment.getAttribute( 'data-autoslide' ) : null;
var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
// Pick value in the following priority order:
// 1. Current fragment's data-autoslide
@@ -3310,27 +4046,34 @@
autoSlide = config.autoSlide;
}
// If there are media elements with data-autoplay,
// automatically set the autoSlide duration to the
- // length of that media
- toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
- if( el.hasAttribute( 'data-autoplay' ) ) {
- if( autoSlide && el.duration * 1000 > autoSlide ) {
- autoSlide = ( el.duration * 1000 ) + 1000;
+ // length of that media. Not applicable if the slide
+ // is divided up into fragments.
+ // playbackRate is accounted for in the duration.
+ if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) {
+ toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
+ if( el.hasAttribute( 'data-autoplay' ) ) {
+ if( autoSlide && (el.duration * 1000 / el.playbackRate ) > autoSlide ) {
+ autoSlide = ( el.duration * 1000 / el.playbackRate ) + 1000;
+ }
}
- }
- } );
+ } );
+ }
// Cue the next auto-slide if:
// - There is an autoSlide value
// - Auto-sliding isn't paused by the user
// - The presentation isn't paused
// - The overview isn't active
// - The presentation isn't over
if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) {
- autoSlideTimeout = setTimeout( navigateNext, autoSlide );
+ autoSlideTimeout = setTimeout( function() {
+ typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext();
+ cueAutoSlide();
+ }, autoSlide );
autoSlideStartTime = Date.now();
}
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
@@ -3472,24 +4215,37 @@
else {
navigateRight();
}
}
- // If auto-sliding is enabled we need to cue up
- // another timeout
- cueAutoSlide();
+ }
+ /**
+ * Checks if the target element prevents the triggering of
+ * swipe navigation.
+ */
+ function isSwipePrevented( target ) {
+
+ while( target && typeof target.hasAttribute === 'function' ) {
+ if( target.hasAttribute( 'data-prevent-swipe' ) ) return true;
+ target = target.parentNode;
+ }
+
+ return false;
+
}
// --------------------------------------------------------------------//
// ----------------------------- EVENTS -------------------------------//
// --------------------------------------------------------------------//
/**
* Called by all event handlers that are based on user
* input.
+ *
+ * @param {object} [event]
*/
function onUserInput( event ) {
if( config.autoSlideStoppable ) {
pauseAutoSlide();
@@ -3497,27 +4253,26 @@
}
/**
* Handler for the document level 'keypress' event.
+ *
+ * @param {object} event
*/
function onDocumentKeyPress( event ) {
// Check if the pressed key is question mark
if( event.shiftKey && event.charCode === 63 ) {
- if( dom.overlay ) {
- closeOverlay();
- }
- else {
- showHelp( true );
- }
+ toggleHelp();
}
}
/**
* Handler for the document level 'keydown' event.
+ *
+ * @param {object} event
*/
function onDocumentKeyDown( event ) {
// If there's a condition specified and it returns false,
// ignore this event
@@ -3532,26 +4287,39 @@
// Check if there's a focused element that could be using
// the keyboard
var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit';
var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName );
+ var activeElementIsNotes = document.activeElement && document.activeElement.className && /speaker-notes/i.test( document.activeElement.className);
// Disregard the event if there's a focused element or a
// keyboard modifier key is present
- if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
+ if( activeElementIsCE || activeElementIsInput || activeElementIsNotes || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
- // While paused only allow "unpausing" keyboard events (b and .)
- if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
+ // While paused only allow resume keyboard events; 'b', 'v', '.'
+ var resumeKeyCodes = [66,86,190,191];
+ var key;
+
+ // Custom key bindings for togglePause should be able to resume
+ if( typeof config.keyboard === 'object' ) {
+ for( key in config.keyboard ) {
+ if( config.keyboard[key] === 'togglePause' ) {
+ resumeKeyCodes.push( parseInt( key, 10 ) );
+ }
+ }
+ }
+
+ if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) {
return false;
}
var triggered = false;
// 1. User defined key bindings
if( typeof config.keyboard === 'object' ) {
- for( var key in config.keyboard ) {
+ for( key in config.keyboard ) {
// Check if this binding matches the pressed key
if( parseInt( key, 10 ) === event.keyCode ) {
var value = config.keyboard[ key ];
@@ -3598,12 +4366,12 @@
case 35: slide( Number.MAX_VALUE ); break;
// space
case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
// return
case 13: isOverview() ? deactivateOverview() : triggered = false; break;
- // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
- case 58: case 59: case 66: case 190: case 191: togglePause(); break;
+ // two-spot, semicolon, b, v, period, Logitech presenter tools "black screen" button
+ case 58: case 59: case 66: case 86: case 190: case 191: togglePause(); break;
// f
case 70: enterFullscreen(); break;
// a
case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
default:
@@ -3636,13 +4404,17 @@
}
/**
* Handler for the 'touchstart' event, enables support for
* swipe and pinch gestures.
+ *
+ * @param {object} event
*/
function onTouchStart( event ) {
+ if( isSwipePrevented( event.target ) ) return true;
+
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
@@ -3659,13 +4431,17 @@
}
/**
* Handler for the 'touchmove' event.
+ *
+ * @param {object} event
*/
function onTouchMove( event ) {
+ if( isSwipePrevented( event.target ) ) return true;
+
// Each touch should only trigger one action
if( !touch.captured ) {
onUserInput( event );
var currentX = event.touches[0].clientX;
@@ -3738,27 +4514,31 @@
}
}
// There's a bug with swiping on some Android devices unless
// the default action is always prevented
- else if( navigator.userAgent.match( /android/gi ) ) {
+ else if( UA.match( /android/gi ) ) {
event.preventDefault();
}
}
/**
* Handler for the 'touchend' event.
+ *
+ * @param {object} event
*/
function onTouchEnd( event ) {
touch.captured = false;
}
/**
* Convert pointer down to touch start.
+ *
+ * @param {object} event
*/
function onPointerDown( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
@@ -3767,10 +4547,12 @@
}
/**
* Convert pointer move to touch move.
+ *
+ * @param {object} event
*/
function onPointerMove( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
@@ -3779,10 +4561,12 @@
}
/**
* Convert pointer up to touch end.
+ *
+ * @param {object} event
*/
function onPointerUp( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
@@ -3792,10 +4576,12 @@
}
/**
* Handles mouse wheel scrolling, throttled to avoid skipping
* multiple slides.
+ *
+ * @param {object} event
*/
function onDocumentMouseScroll( event ) {
if( Date.now() - lastMouseWheelStep > 600 ) {
@@ -3803,11 +4589,11 @@
var delta = event.detail || -event.wheelDelta;
if( delta > 0 ) {
navigateNext();
}
- else {
+ else if( delta < 0 ) {
navigatePrev();
}
}
@@ -3816,20 +4602,26 @@
/**
* Clicking on the progress bar results in a navigation to the
* closest approximate horizontal slide using this equation:
*
* ( clickX / presentationWidth ) * numberOfSlides
+ *
+ * @param {object} event
*/
function onProgressClicked( event ) {
onUserInput( event );
event.preventDefault();
var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
+ if( config.rtl ) {
+ slideIndex = slidesTotal - slideIndex;
+ }
+
slide( slideIndex );
}
/**
@@ -3842,46 +4634,57 @@
function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
/**
* Handler for the window level 'hashchange' event.
+ *
+ * @param {object} [event]
*/
function onWindowHashChange( event ) {
readURL();
}
/**
* Handler for the window level 'resize' event.
+ *
+ * @param {object} [event]
*/
function onWindowResize( event ) {
layout();
}
/**
* Handle for the window level 'visibilitychange' event.
+ *
+ * @param {object} [event]
*/
function onPageVisibilityChange( event ) {
var isHidden = document.webkitHidden ||
document.msHidden ||
document.hidden;
// If, after clicking a link or similar and we're coming back,
// focus the document.body to ensure we can use keyboard shortcuts
if( isHidden === false && document.activeElement !== document.body ) {
- document.activeElement.blur();
+ // Not all elements support .blur() - SVGs among them.
+ if( typeof document.activeElement.blur === 'function' ) {
+ document.activeElement.blur();
+ }
document.body.focus();
}
}
/**
* Invoked when a slide is and we're in the overview.
+ *
+ * @param {object} event
*/
function onOverviewSlideClicked( event ) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
@@ -3911,10 +4714,12 @@
}
/**
* Handles clicks on links that are set to preview in the
* iframe overlay.
+ *
+ * @param {object} event
*/
function onPreviewLinkClicked( event ) {
if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) {
var url = event.currentTarget.getAttribute( 'href' );
@@ -3926,10 +4731,12 @@
}
/**
* Handles click on the auto-sliding controls element.
+ *
+ * @param {object} [event]
*/
function onAutoSlidePlayerClick( event ) {
// Replay
if( Reveal.isLastSlide() && config.loop === false ) {
@@ -3957,19 +4764,20 @@
* Constructor for the playback component, which displays
* play/pause/progress controls.
*
* @param {HTMLElement} container The component will append
* itself to this
- * @param {Function} progressCheck A method which will be
+ * @param {function} progressCheck A method which will be
* called frequently to get the current progress on a range
* of 0-1
*/
function Playback( container, progressCheck ) {
// Cosmetics
- this.diameter = 50;
- this.thickness = 3;
+ this.diameter = 100;
+ this.diameter2 = this.diameter/2;
+ this.thickness = 6;
// Flags if we are currently playing
this.playing = false;
// Current progress on a 0-1 range
@@ -3983,18 +4791,23 @@
this.canvas = document.createElement( 'canvas' );
this.canvas.className = 'playback';
this.canvas.width = this.diameter;
this.canvas.height = this.diameter;
+ this.canvas.style.width = this.diameter2 + 'px';
+ this.canvas.style.height = this.diameter2 + 'px';
this.context = this.canvas.getContext( '2d' );
this.container.appendChild( this.canvas );
this.render();
}
+ /**
+ * @param value
+ */
Playback.prototype.setPlaying = function( value ) {
var wasPlaying = this.playing;
this.playing = value;
@@ -4033,14 +4846,14 @@
* Renders the current progress and playback state.
*/
Playback.prototype.render = function() {
var progress = this.playing ? this.progress : 0,
- radius = ( this.diameter / 2 ) - this.thickness,
- x = this.diameter / 2,
- y = this.diameter / 2,
- iconSize = 14;
+ radius = ( this.diameter2 ) - this.thickness,
+ x = this.diameter2,
+ y = this.diameter2,
+ iconSize = 28;
// Ease towards 1
this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
@@ -4049,11 +4862,11 @@
this.context.save();
this.context.clearRect( 0, 0, this.diameter, this.diameter );
// Solid background color
this.context.beginPath();
- this.context.arc( x, y, radius + 2, 0, Math.PI * 2, false );
+ this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false );
this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
this.context.fill();
// Draw progress track
this.context.beginPath();
@@ -4074,18 +4887,18 @@
this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
// Draw play/pause icons
if( this.playing ) {
this.context.fillStyle = '#fff';
- this.context.fillRect( 0, 0, iconSize / 2 - 2, iconSize );
- this.context.fillRect( iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize );
+ this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize );
+ this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize );
}
else {
this.context.beginPath();
- this.context.translate( 2, 0 );
+ this.context.translate( 4, 0 );
this.context.moveTo( 0, 0 );
- this.context.lineTo( iconSize - 2, iconSize / 2 );
+ this.context.lineTo( iconSize - 4, iconSize / 2 );
this.context.lineTo( 0, iconSize );
this.context.fillStyle = '#fff';
this.context.fill();
}
@@ -4116,10 +4929,12 @@
// ------------------------------- API --------------------------------//
// --------------------------------------------------------------------//
Reveal = {
+ VERSION: VERSION,
+
initialize: initialize,
configure: configure,
sync: sync,
// Navigation methods
@@ -4146,16 +4961,22 @@
navigateNext: navigateNext,
// Forces an update in slide layout
layout: layout,
+ // Randomizes the order of slides
+ shuffle: shuffle,
+
// Returns an object with the available routes as booleans (left/right/top/bottom)
availableRoutes: availableRoutes,
// Returns an object with the available fragments as booleans (prev/next)
availableFragments: availableFragments,
+ // Toggles a help overlay with keyboard shortcuts
+ toggleHelp: toggleHelp,
+
// Toggles the overview mode on/off
toggleOverview: toggleOverview,
// Toggles the "black screen" mode on/off
togglePause: togglePause,
@@ -4174,24 +4995,34 @@
// Facility for persisting and restoring the presentation state
getState: getState,
setState: setState,
+ // Presentation progress
+ getSlidePastCount: getSlidePastCount,
+
// Presentation progress on range of 0-1
getProgress: getProgress,
// Returns the indices of the current, or specified, slide
getIndices: getIndices,
+ // Returns an Array of all slides
+ getSlides: getSlides,
+
+ // Returns the total number of slides
getTotalSlides: getTotalSlides,
// Returns the slide element at the specified index
getSlide: getSlide,
// Returns the slide background element at the specified index
getSlideBackground: getSlideBackground,
+ // Returns the speaker notes string for a slide, or null
+ getSlideNotes: getSlideNotes,
+
// Returns the previous slide element, may be null
getPreviousSlide: function() {
return previousSlide;
},
@@ -4266,9 +5097,14 @@
},
// Programatically triggers a keyboard event
triggerKey: function( keyCode ) {
onDocumentKeyDown( { keyCode: keyCode } );
+ },
+
+ // Registers a new shortcut to include in the help overlay
+ registerKeyboardShortcut: function( key, value ) {
+ keyboardShortcuts[key] = value;
}
};
return Reveal;