diff --git a/.gitignore b/.gitignore index 9ffdbc7..e7b4f21 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,13 @@ +.idea/ +*.iml +*.iws +*.eml +out/ .DS_Store .svn log/*.log tmp/** node_modules/ -.sass-cache \ No newline at end of file +.sass-cache +css/reveal.min.css +js/reveal.min.js \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 2d6cd8f..264c6ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: node_js node_js: - - 0.8 + - 4.1.1 before_script: - npm install -g grunt-cli \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c2091e8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/Gruntfile.js b/Gruntfile.js index 13f3dde..7cea2a5 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,6 +1,8 @@ /* global module:false */ module.exports = function(grunt) { var port = grunt.option('port') || 8000; + var base = grunt.option('base') || '.'; + // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), @@ -11,7 +13,7 @@ module.exports = function(grunt) { ' * http://lab.hakim.se/reveal-js\n' + ' * MIT licensed\n' + ' *\n' + - ' * Copyright (C) 2013 Hakim El Hattab, http://hakim.se\n' + + ' * Copyright (C) 2016 Hakim El Hattab, http://hakim.se\n' + ' */' }, @@ -29,6 +31,31 @@ module.exports = function(grunt) { } }, + sass: { + core: { + files: { + 'css/reveal.css': 'css/reveal.scss', + } + }, + themes: { + files: [ + { + expand: true, + cwd: 'css/theme/source', + src: ['*.scss'], + dest: 'css/theme', + ext: '.css' + } + ] + } + }, + + autoprefixer: { + dist: { + src: 'css/reveal.css' + } + }, + cssmin: { compress: { files: { @@ -37,22 +64,6 @@ module.exports = function(grunt) { } }, - sass: { - main: { - files: { - 'css/theme/default.css': 'css/theme/source/default.scss', - 'css/theme/beige.css': 'css/theme/source/beige.scss', - 'css/theme/night.css': 'css/theme/source/night.scss', - 'css/theme/serif.css': 'css/theme/source/serif.scss', - 'css/theme/simple.css': 'css/theme/source/simple.scss', - 'css/theme/sky.css': 'css/theme/source/sky.scss', - 'css/theme/moon.css': 'css/theme/source/moon.scss', - 'css/theme/solarized.css': 'css/theme/source/solarized.scss', - 'css/theme/blood.css': 'css/theme/source/blood.scss' - } - } - }, - jshint: { options: { curly: false, @@ -70,7 +81,9 @@ module.exports = function(grunt) { head: false, module: false, console: false, - unescape: false + unescape: false, + define: false, + exports: false } }, files: [ 'Gruntfile.js', 'js/reveal.js' ] @@ -80,9 +93,9 @@ module.exports = function(grunt) { server: { options: { port: port, - base: '.', - livereload: true, - open: true + base: base, + livereload: true, + open: true } } }, @@ -94,25 +107,39 @@ module.exports = function(grunt) { 'js/**', 'lib/**', 'images/**', - 'plugin/**' + 'plugin/**', + '**.md' ] }, watch: { - options: { - livereload: true - }, - main: { - files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], - tasks: 'default' + js: { + files: [ 'Gruntfile.js', 'js/reveal.js' ], + tasks: 'js' }, theme: { files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], - tasks: 'themes' + tasks: 'css-themes' }, - html: { - files: [ 'index.html'] - } + css: { + files: [ 'css/reveal.scss' ], + tasks: 'css-core' + }, + html: { + files: [ '*.html'] + }, + markdown: { + files: [ '*.md' ] + }, + options: { + livereload: true + } + }, + + retire: { + js: ['js/reveal.js', 'lib/js/*.js', 'plugin/**/*.js'], + node: ['.'], + options: {} } }); @@ -123,15 +150,26 @@ module.exports = function(grunt) { grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); grunt.loadNpmTasks( 'grunt-contrib-uglify' ); grunt.loadNpmTasks( 'grunt-contrib-watch' ); - grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-sass' ); grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-autoprefixer' ); grunt.loadNpmTasks( 'grunt-zip' ); + grunt.loadNpmTasks( 'grunt-retire' ); // Default task - grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + grunt.registerTask( 'default', [ 'css', 'js' ] ); - // Theme task - grunt.registerTask( 'themes', [ 'sass' ] ); + // JS task + grunt.registerTask( 'js', [ 'jshint', 'uglify', 'qunit' ] ); + + // Theme CSS + grunt.registerTask( 'css-themes', [ 'sass:themes' ] ); + + // Core framework CSS + grunt.registerTask( 'css-core', [ 'sass:core', 'autoprefixer', 'cssmin' ] ); + + // All CSS + grunt.registerTask( 'css', [ 'sass', 'autoprefixer', 'cssmin' ] ); // Package presentation to archive grunt.registerTask( 'package', [ 'default', 'zip' ] ); diff --git a/LICENSE b/LICENSE index e1e8bf7..faadd00 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (C) 2013 Hakim El Hattab, http://hakim.se +Copyright (C) 2016 Hakim El Hattab, http://hakim.se Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index b7bb0d3..cb72f23 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,95 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.png?branch=master)](https://travis-ci.org/hakimel/reveal.js) +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) Slides A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a browser with support for CSS 3D transforms but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). There's also a fully featured visual editor and platform for sharing reveal.js presentations at [slides.com](https://slides.com?ref=github). +## Table of contents +- [Online Editor](#online-editor) +- [Instructions](#instructions) + - [Markup](#markup) + - [Markdown](#markdown) + - [Element Attributes](#element-attributes) + - [Slide Attributes](#slide-attributes) +- [Configuration](#configuration) +- [Presentation Size](#presentation-size) +- [Dependencies](#dependencies) +- [Ready Event](#ready-event) +- [Auto-sliding](#auto-sliding) +- [Keyboard Bindings](#keyboard-bindings) +- [Touch Navigation](#touch-navigation) +- [Lazy Loading](#lazy-loading) +- [API](#api) + - [Slide Changed Event](#slide-changed-event) + - [Presentation State](#presentation-state) + - [Slide States](#slide-states) + - [Slide Backgrounds](#slide-backgrounds) + - [Parallax Background](#parallax-background) + - [Slide Transitions](#slide-transitions) + - [Internal links](#internal-links) + - [Fragments](#fragments) + - [Fragment events](#fragment-events) + - [Code syntax highlighting](#code-syntax-highlighting) + - [Slide number](#slide-number) + - [Overview mode](#overview-mode) + - [Fullscreen mode](#fullscreen-mode) + - [Embedded media](#embedded-media) + - [Stretching elements](#stretching-elements) + - [postMessage API](#postmessage-api) +- [PDF Export](#pdf-export) +- [Theming](#theming) +- [Speaker Notes](#speaker-notes) + - [Share and Print Speaker Notes](#share-and-print-speaker-notes) + - [Server Side Speaker Notes](#server-side-speaker-notes) +- [Multiplexing](#multiplexing) + - [Master presentation](#master-presentation) + - [Client presentation](#client-presentation) + - [Socket.io server](#socketio-server) +- [MathJax](#mathjax) +- [Installation](#installation) + - [Basic setup](#basic-setup) + - [Full setup](#full-setup) + - [Folder Structure](#folder-structure) +- [License](#license) -#### More reading: -- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +#### More reading - [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. - [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! - [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. ## Online Editor -Presentations are written using HTML or markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slid.es](http://slid.es). +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [https://slides.com](https://slides.com?ref=github). ## Instructions ### Markup -Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: +Here's a barebones example of a fully working reveal.js presentation: +```html + + + + + + +
+
+
Slide 1
+
Slide 2
+
+
+ + + + +``` + +The presentation markup hierarchy needs to be `.reveal > .slides > section` where the `section` represents one slide and can be repeated indefinitely. If you place multiple `section` elements inside of another `section` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and will be included in the horizontal sequence. For example: ```html
@@ -36,9 +105,9 @@ Markup hierarchy needs to be ``
``` elements and wrap the contents in a ```
``` @@ -129,6 +198,9 @@ Reveal.initialize({ // 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, @@ -136,6 +208,13 @@ Reveal.initialize({ // i.e. contained within a limited portion of the screen embedded: false, + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Flags if speaker notes should be visible to all viewers + showNotes: false, + // 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 @@ -144,6 +223,9 @@ Reveal.initialize({ // Stop auto-sliding after user input autoSlideStoppable: true, + // Use this method for navigation when auto-sliding + autoSlideMethod: Reveal.navigateNext, + // Enable slide navigation via mouse wheel mouseWheel: false, @@ -154,13 +236,13 @@ Reveal.initialize({ previewLinks: false, // Transition style - transition: 'default', // default/cube/page/concave/zoom/linear/fade/none + transition: 'default', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds - backgroundTransition: 'default', // default/none/slide/concave/convex/zoom + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom // Number of slides away from the current that are visible viewDistance: 3, @@ -169,14 +251,17 @@ Reveal.initialize({ parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" // Parallax background size - parallaxBackgroundSize: '' // CSS syntax, e.g. "2100px 900px" + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + // Number of pixels to move the parallax background per slide + // - Calculated automatically unless specified + // - Set to 0 to disable movement along an axis + parallaxBackgroundHorizontal: null, + parallaxBackgroundVertical: null }); ``` -Note that the new default vertical centering option will break compatibility with slides that were using transitions with backgrounds (`cube` and `page`). To restore the previous behavior, set `center` to `false`. - The configuration can be updated after initialization using the ```configure``` method: @@ -189,45 +274,6 @@ Reveal.configure({ autoSlide: 5000 }); ``` -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }, - - // Remote control your reveal.js presentation using a touch device - { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - - ### Presentation Size All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. @@ -250,15 +296,63 @@ Reveal.initialize({ // Bounds for smallest/largest possible scale to apply to content minScale: 0.2, - maxScale: 1.0 + maxScale: 1.5 }); ``` +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + +Note that we also add a `.ready` class to the `.reveal` element so that you can hook into this with CSS. + ### Auto-sliding -Presentations can be configure to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: ```javascript // Slide every five seconds @@ -266,15 +360,22 @@ Reveal.configure({ autoSlide: 5000 }); ``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. -When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Sliding is also paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. - -You can also override the slide duration for individual slides by using the ```data-autoslide``` attribute on individual sections: +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: ```html -
This will remain on screen for 10 seconds
+
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
``` +To override the method used for navigation when auto-sliding, you can specify the ```autoSlideMethod``` setting. To only navigate along the top layer and ignore vertical slides, set this to ```Reveal.navigateRight```. + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + ### Keyboard Bindings @@ -290,10 +391,34 @@ Reveal.configure({ }); ``` +### Touch Navigation + +You can swipe to navigate through a presentation on any touch-enabled device. Horizontal swipes change between horizontal slides, vertical swipes change between vertical slides. If you wish to disable this you can set the `touch` config option to false when initializing reveal.js. + +If there's some part of your content that needs to remain accessible to touch events you'll need to highlight this by adding a `data-prevent-swipe` attribute to the element. One common example where this is useful is elements that need to be scrolled. + + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + ### API -The ``Reveal`` class provides a JavaScript API for controlling navigation and reading state: +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: ```javascript // Navigation @@ -306,35 +431,49 @@ Reveal.prev(); Reveal.next(); Reveal.prevFragment(); Reveal.nextFragment(); + +// Randomize the order of slides +Reveal.shuffle(); + +// Shows a help overlay with keyboard shortcuts +Reveal.showHelp(); + +// Toggle presentation states, optionally pass true/false to force on/off Reveal.toggleOverview(); Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); // Retrieves the previous and current slide elements Reveal.getPreviousSlide(); Reveal.getCurrentSlide(); Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// Returns the speaker notes for the current slide +Reveal.getSlideNotes(); // State checks Reveal.isFirstSlide(); Reveal.isLastSlide(); Reveal.isOverview(); Reveal.isPaused(); -``` - -### Ready Event - -The 'ready' event is fired when reveal.js has loaded all (synchronous) dependencies and is ready to start navigating. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); +Reveal.isAutoSliding(); ``` ### Slide Changed Event -An 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. @@ -344,8 +483,24 @@ Reveal.addEventListener( 'slidechanged', function( event ) { } ); ``` +### Presentation State -### States +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. @@ -359,26 +514,64 @@ Reveal.addEventListener( 'somestate', function() { ### Slide Backgrounds -Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page background colors or images by applying a ```data-background``` attribute to your ```
``` elements. Below are a few examples. +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. +##### Color Backgrounds +All CSS color formats are supported, like rgba() or hsl(). ```html -
-

All CSS color formats are supported, like rgba() or hsl().

-
-
-

This slide will have a full-size background image.

-
-
-

This background image will be sized to 100px and repeated.

+
+

Color

``` +##### Image Backgrounds +By default, background images are resized to cover the full page. Available options: + +| Attribute | Default | Description | +| :--------------------------- | :--------- | :---------- | +| data-background-image | | URL of the image to show. GIFs restart when the slide opens. | +| data-background-size | cover | See [background-size](https://developer.mozilla.org/docs/Web/CSS/background-size) on MDN. | +| data-background-position | center | See [background-position](https://developer.mozilla.org/docs/Web/CSS/background-position) on MDN. | +| data-background-repeat | no-repeat | See [background-repeat](https://developer.mozilla.org/docs/Web/CSS/background-repeat) on MDN. | +```html +
+

Image

+
+
+

This background image will be sized to 100px and repeated

+
+``` + +##### Video Backgrounds +Automatically plays a full size video behind the slide. + +| Attribute | Default | Description | +| :--------------------------- | :------ | :---------- | +| data-background-video | | A single video source, or a comma separated list of video sources. | +| data-background-video-loop | false | Flags if the video should play repeatedly. | +| data-background-video-muted | false | Flags if the audio should be muted. | + +```html +
+

Video

+
+``` + +##### Iframe Backgrounds +Embeds a web page as a background. Note that since the iframe is in the background layer, behind your slides, it is not possible to interact with the embedded page. +```html +
+

Iframe

+
+``` + +##### Background Transitions Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. ### Parallax Background -If you want to use a parallax scrolling background, set the two following config properties when initializing reveal.js (the third one is optional). +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). ```javascript Reveal.initialize({ @@ -389,8 +582,11 @@ Reveal.initialize({ // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) - // This slide transition gives best results: - transition: linear + // Number of pixels to move the parallax background per slide + // - Calculated automatically unless specified + // - Set to 0 to disable movement along an axis + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 }); ``` @@ -412,7 +608,25 @@ The global presentation transition is set using the ```transition``` config valu
``` -Note that this does not work with the page and cube transitions. +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` ### Internal links @@ -445,8 +659,8 @@ The default fragment style is to start out invisible and fade in. This style can

grow

shrink

-

roll-in

fade-out

+

fade-up (also down, left and right!)

visible only once

blue only once

highlight-red

@@ -492,15 +706,15 @@ Reveal.addEventListener( 'fragmenthidden', function( event ) { ### Code syntax highlighting -By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. +By default, Reveal is configured with [highlight.js](https://highlightjs.org/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present, surrounding whitespace is automatically removed. HTML will be escaped by default. To avoid this, for example if you are using `` to call out a line of code, add the `data-noescape` attribute to the `` element. ```html
-

+	

 (def lazy-fib
   (concat
    [0 1]
-   ((fn rfib [a b]
+   ((fn rfib [a b]
         (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
 	
@@ -510,7 +724,16 @@ By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/ If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. ```javascript +// Shows the slide number using default formatting Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// "h.v": horizontal . vertical slide number (default) +// "h/v": horizontal / vertical slide number +// "c": flattened slide number +// "c/t": flattened slide number / total slides +Reveal.configure({ slideNumber: 'c/t' }); + ``` @@ -558,36 +781,76 @@ Limitations: - Only one descendant per slide section can be stretched +### postMessage API +The framework has a built-in postMessage API that can be used when communicating with a presentation inside of another window. Here's an example showing how you'd make a reveal.js instance in the given window proceed to slide 2: + +```javascript +.postMessage( JSON.stringify({ method: 'slide', args: [ 2 ] }), '*' ); +``` + +When reveal.js runs inside of an iframe it can optionally bubble all of its events to the parent. Bubbled events are stringified JSON with three fields: namespace, eventName and state. Here's how you subscribe to them from the parent window: + +```javascript +window.addEventListener( 'message', function( event ) { + var data = JSON.parse( event.data ); + if( data.namespace === 'reveal' && data.eventName ==='slidechanged' ) { + // Slide changed, see data.state for slide number + } +} ); +``` + +This cross-window messaging can be toggled on or off using configuration flags. + +```javascript +Reveal.initialize({ + ..., + + // Exposes the reveal.js API through window.postMessage + postMessage: true, + + // Dispatches all reveal.js events to the parent window through postMessage + postMessageEvents: false +}); +``` + + ## PDF Export -Presentations can be exported to PDF via a special print stylesheet. This feature requires that you use [Google Chrome](http://google.com/chrome). -Here's an example of an exported presentation that's been uploaded to SlideShare: http://www.slideshare.net/hakimel/revealjs-13872948. +Presentations can be exported to PDF via a special print stylesheet. This feature requires that you use [Google Chrome](http://google.com/chrome) or [Chromium](https://www.chromium.org/Home) and to be serving the presention from a webserver. +Here's an example of an exported presentation that's been uploaded to SlideShare: http://www.slideshare.net/hakimel/revealjs-300. -1. Open your presentation with [css/print/pdf.css](https://github.com/hakimel/reveal.js/blob/master/css/print/pdf.css) included on the page. The default index HTML lets you add *print-pdf* anywhere in the query to include the stylesheet, for example: [lab.hakim.se/reveal-js?print-pdf](http://lab.hakim.se/reveal-js?print-pdf). -2. Open the in-browser print dialog (CMD+P). +Export dimensions are inferred from the configured [presentation size](#presentation-size). Slides that are too tall to fit within a single page will expand onto multiple pages. You can limit how many pages a slide may expand onto using the `pdfMaxPagesPerSlide` config option, for example `Reveal.configure({ pdfMaxPagesPerSlide: 1 })` ensures that no slide ever grows to more than one printed page. + +1. Open your presentation with `print-pdf` included in the query string i.e. http://localhost:8000/?print-pdf#/. This triggers the default index HTML to load the PDF print stylesheet ([css/print/pdf.css](https://github.com/hakimel/reveal.js/blob/master/css/print/pdf.css)). You can test this with [lab.hakim.se/reveal-js?print-pdf](http://lab.hakim.se/reveal-js?print-pdf). +2. Open the in-browser print dialog (CTRL/CMD+P). 3. Change the **Destination** setting to **Save as PDF**. 4. Change the **Layout** to **Landscape**. 5. Change the **Margins** to **None**. -6. Click **Save**. +6. Enable the **Background graphics** option. +7. Click **Save**. -![Chrome Print Settings](https://s3.amazonaws.com/hakim-static/reveal-js/pdf-print-settings.png) +![Chrome Print Settings](https://s3.amazonaws.com/hakim-static/reveal-js/pdf-print-settings-2.png) + +Alternatively you can use the [decktape](https://github.com/astefanutti/decktape) project. ## Theming The framework comes with a few different themes included: -- default: Gray background, white text, blue links +- black: Black background, white text, blue links (default theme) +- white: White background, black text, blue links +- league: Gray background, white text, blue links (default theme for reveal.js < 3.0.0) - beige: Beige background, dark text, brown links -- sky: Blue background, thin white text, blue links +- sky: Blue background, thin dark text, blue links - night: Black background, thick white text, orange links - serif: Cappuccino background, gray text, brown links - simple: White background, black text, blue links - solarized: Cream-colored background, dark green text, blue links -Each theme is available as a separate stylesheet. To change theme you will need to replace **default** below with your desired theme name in index.html: +Each theme is available as a separate stylesheet. To change theme you will need to replace **black** below with your desired theme name in index.html: ```html - + ``` If you want to add a theme of your own see the instructions here: [/css/theme/README.md](https://github.com/hakimel/reveal.js/blob/master/css/theme/README.md). @@ -597,8 +860,12 @@ If you want to add a theme of your own see the instructions here: [/css/theme/RE reveal.js comes with a speaker notes plugin which can be used to present per-slide notes in a separate browser window. The notes window also gives you a preview of the next upcoming slide so it may be helpful even if you haven't written any notes. Press the 's' key on your keyboard to open the notes window. +A speaker timer starts as soon as the speaker view is opened. You can reset it to 00:00:00 at any time by simply clicking/tapping on it. + Notes are defined by appending an ```
' ].join(''); - dom.preview.querySelector( 'iframe' ).addEventListener( 'load', function( event ) { - dom.preview.classList.add( 'loaded' ); + dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) { + dom.overlay.classList.add( 'loaded' ); }, false ); - dom.preview.querySelector( '.close' ).addEventListener( 'click', function( event ) { - closePreview(); + dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { + closeOverlay(); event.preventDefault(); }, false ); - dom.preview.querySelector( '.external' ).addEventListener( 'click', function( event ) { - closePreview(); + dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) { + closeOverlay(); }, false ); setTimeout( function() { - dom.preview.classList.add( 'visible' ); + dom.overlay.classList.add( 'visible' ); }, 1 ); } /** - * Closes the iframe preview window. + * Opens a overlay window with help material. */ - function closePreview() { + function showHelp() { - if( dom.preview ) { - dom.preview.setAttribute( 'src', '' ); - dom.preview.parentNode.removeChild( dom.preview ); - dom.preview = null; + if( config.help ) { + + closeOverlay(); + + dom.overlay = document.createElement( 'div' ); + dom.overlay.classList.add( 'overlay' ); + dom.overlay.classList.add( 'overlay-help' ); + dom.wrapper.appendChild( dom.overlay ); + + var html = '

Keyboard Shortcuts


'; + + html += ''; + for( var key in keyboardShortcuts ) { + html += ''; + } + + html += '
KEYACTION
' + key + '' + keyboardShortcuts[ key ] + '
'; + + dom.overlay.innerHTML = [ + '
', + '', + '
', + '
', + '
'+ html +'
', + '
' + ].join(''); + + dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { + closeOverlay(); + event.preventDefault(); + }, false ); + + setTimeout( function() { + dom.overlay.classList.add( 'visible' ); + }, 1 ); + + } + + } + + /** + * Closes any currently open overlay. + */ + function closeOverlay() { + + if( dom.overlay ) { + dom.overlay.parentNode.removeChild( dom.overlay ); + dom.overlay = null; } } @@ -1041,54 +1575,55 @@ var Reveal = (function(){ if( dom.wrapper && !isPrintingPDF() ) { - // Available space to scale within - var availableWidth = dom.wrapper.offsetWidth, - availableHeight = dom.wrapper.offsetHeight; - - // Reduce available space by margin - availableWidth -= ( availableHeight * config.margin ); - availableHeight -= ( availableHeight * config.margin ); - - // Dimensions of the content - var slideWidth = config.width, - slideHeight = config.height, - slidePadding = 20; // TODO Dig this out of DOM + var size = getComputedSlideSize(); // Layout the contents of the slides - layoutSlideContents( config.width, config.height, slidePadding ); + layoutSlideContents( config.width, config.height ); - // Slide width may be a percentage of available width - if( typeof slideWidth === 'string' && /%$/.test( slideWidth ) ) { - slideWidth = parseInt( slideWidth, 10 ) / 100 * availableWidth; - } - - // Slide height may be a percentage of available height - if( typeof slideHeight === 'string' && /%$/.test( slideHeight ) ) { - slideHeight = parseInt( slideHeight, 10 ) / 100 * availableHeight; - } - - dom.slides.style.width = slideWidth + 'px'; - dom.slides.style.height = slideHeight + 'px'; + dom.slides.style.width = size.width + 'px'; + dom.slides.style.height = size.height + 'px'; // Determine scale of content to fit within available space - scale = Math.min( availableWidth / slideWidth, availableHeight / slideHeight ); + scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); // Respect max/min scale settings scale = Math.max( scale, config.minScale ); scale = Math.min( scale, config.maxScale ); - // Prefer applying scale via zoom since Chrome blurs scaled content - // with nested transforms - if( typeof dom.slides.style.zoom !== 'undefined' && !navigator.userAgent.match( /(iphone|ipod|ipad|android)/gi ) ) { - dom.slides.style.zoom = scale; + // Don't apply any scaling styles if scale is 1 + if( scale === 1 ) { + dom.slides.style.zoom = ''; + 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 { - transformElement( dom.slides, 'translate(-50%, -50%) scale('+ scale +') translate(50%, 50%)' ); + // 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'; + transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } ); + } } // Select all slides, vertical and horizontal - var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) ); + var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ); for( var i = 0, len = slides.length; i < len; i++ ) { var slide = slides[ i ]; @@ -1105,7 +1640,7 @@ var Reveal = (function(){ slide.style.top = 0; } else { - slide.style.top = Math.max( - ( getAbsoluteHeight( slide ) / 2 ) - slidePadding, -slideHeight / 2 ) + 'px'; + slide.style.top = Math.max( ( size.height - slide.scrollHeight ) / 2, 0 ) + 'px'; } } else { @@ -1125,13 +1660,13 @@ var Reveal = (function(){ * Applies layout logic to the contents of all slides in * the presentation. */ - 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 - var remainingHeight = getRemainingHeight( element, ( height - ( padding * 2 ) ) ); + var remainingHeight = getRemainingHeight( element, height ); // Consider the aspect ratio of media elements if( /(img|video)/gi.test( element.nodeName ) ) { @@ -1153,6 +1688,41 @@ var Reveal = (function(){ } + /** + * Calculates the computed pixel size of our slides. These + * values are based on the width and height configuration + * options. + */ + function getComputedSlideSize( presentationWidth, presentationHeight ) { + + var size = { + // Slide size + width: config.width, + height: config.height, + + // Presentation size + presentationWidth: presentationWidth || dom.wrapper.offsetWidth, + presentationHeight: presentationHeight || dom.wrapper.offsetHeight + }; + + // Reduce available space by 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; + } + + // Slide height may be a percentage of available height + if( typeof size.height === 'string' && /%$/.test( size.height ) ) { + size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight; + } + + return size; + + } + /** * Stores the vertical index of a stack so that the same * vertical slide can be selected when navigating to and @@ -1190,94 +1760,117 @@ var Reveal = (function(){ } /** - * 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() ) { - // Don't auto-slide while in overview mode - cancelAutoSlide(); - - var wasActive = dom.wrapper.classList.contains( 'overview' ); - - // Vary the depth of the overview based on screen size - var depth = window.innerWidth < 400 ? 1000 : 2500; + overview = true; dom.wrapper.classList.add( 'overview' ); dom.wrapper.classList.remove( 'overview-deactivating' ); - clearTimeout( activateOverviewTimeout ); - clearTimeout( deactivateOverviewTimeout ); + if( features.overviewTransitions ) { + setTimeout( function() { + dom.wrapper.classList.add( 'overview-animated' ); + }, 1 ); + } - // Not the pretties solution, but need to let the overview - // class apply first so that slides are measured accurately - // before we can position them - activateOverviewTimeout = setTimeout( function() { + // Don't auto-slide while in overview mode + cancelAutoSlide(); - var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); + // Move the backgrounds element into the slide container to + // that the same scaling is applied + dom.slides.appendChild( dom.background ); - for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) { - var hslide = horizontalSlides[i], - hoffset = config.rtl ? -105 : 105; - - hslide.setAttribute( 'data-index-h', i ); - - // Apply CSS transform - transformElement( hslide, 'translateZ(-'+ depth +'px) translate(' + ( ( i - indexh ) * hoffset ) + '%, 0%)' ); - - 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 ); - - var vslide = verticalSlides[j]; - - vslide.setAttribute( 'data-index-h', i ); - vslide.setAttribute( 'data-index-v', j ); - - // Apply CSS transform - transformElement( vslide, 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)' ); - - // Navigate to this slide on click - vslide.addEventListener( 'click', onOverviewSlideClicked, true ); - } - - } - else { - - // Navigate to this slide on click - hslide.addEventListener( 'click', onOverviewSlideClicked, true ); - - } + // 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 ); } + } ); - updateSlidesVisibility(); + // Calculate slide sizes + var margin = 70; + var slideSize = getComputedSlideSize(); + overviewSlideWidth = slideSize.width + margin; + overviewSlideHeight = slideSize.height + margin; - layout(); + // Reverse in RTL mode + if( config.rtl ) { + overviewSlideWidth = -overviewSlideWidth; + } - if( !wasActive ) { - // Notify observers of the overview showing - dispatchEvent( 'overviewshown', { - 'indexh': indexh, - 'indexv': indexv, - 'currentSlide': currentSlide - } ); - } + updateSlidesVisibility(); + layoutOverview(); + updateOverview(); - }, 10 ); + layout(); + + // Notify observers of the overview showing + dispatchEvent( 'overviewshown', { + 'indexh': indexh, + 'indexv': indexv, + 'currentSlide': currentSlide + } ); } } + /** + * Uses CSS transforms to position all slides in a grid for + * display inside of the overview mode. + */ + function layoutOverview() { + + // 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)' ); + + 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 ); + + transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' ); + } ); + + } + } ); + + // 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)' ); + } ); + } ); + + } + + /** + * Moves the overview viewport to the current slides. + * Called each time the current slide changes. + */ + function updateOverview() { + + transformSlides( { + overview: [ + 'translateX('+ ( -indexh * overviewSlideWidth ) +'px)', + 'translateY('+ ( -indexv * overviewSlideHeight ) +'px)', + 'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)' + ].join( ' ' ) + } ); + + } + /** * Exits the slide overview and enters the currently * active slide. @@ -1287,30 +1880,41 @@ var Reveal = (function(){ // Only proceed if enabled in config if( config.overview ) { - clearTimeout( activateOverviewTimeout ); - clearTimeout( deactivateOverviewTimeout ); + 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' ); - deactivateOverviewTimeout = setTimeout( function () { + setTimeout( function () { dom.wrapper.classList.remove( 'overview-deactivating' ); }, 1 ); - // Select all slides - toArray( document.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { - // Resets all transforms to use the external styles + // 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 ) { 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 @@ -1349,7 +1953,7 @@ var Reveal = (function(){ */ function isOverview() { - return dom.wrapper.classList.contains( 'overview' ); + return overview; } @@ -1377,14 +1981,14 @@ var Reveal = (function(){ */ 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; + element.msRequestFullscreen; if( requestMethod ) { requestMethod.apply( element ); @@ -1398,13 +2002,15 @@ var Reveal = (function(){ */ function pause() { - var wasPaused = dom.wrapper.classList.contains( 'paused' ); + if( config.pause ) { + var wasPaused = dom.wrapper.classList.contains( 'paused' ); - cancelAutoSlide(); - dom.wrapper.classList.add( 'paused' ); + cancelAutoSlide(); + dom.wrapper.classList.add( 'paused' ); - if( wasPaused === false ) { - dispatchEvent( 'paused' ); + if( wasPaused === false ) { + dispatchEvent( 'paused' ); + } } } @@ -1428,13 +2034,13 @@ var Reveal = (function(){ /** * Toggles the paused mode on and off. */ - function togglePause() { + function togglePause( override ) { - if( isPaused() ) { - resume(); + if( typeof override === 'boolean' ) { + override ? pause() : resume(); } else { - pause(); + isPaused() ? resume() : pause(); } } @@ -1448,6 +2054,34 @@ var Reveal = (function(){ } + /** + * Toggles the auto slide mode on and off. + * + * @param {Boolean} override Optional flag which sets the desired state. + * True means autoplay starts, false means it stops. + */ + + function toggleAutoSlide( override ) { + + if( typeof override === 'boolean' ) { + override ? resumeAutoSlide() : pauseAutoSlide(); + } + + else { + autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide(); + } + + } + + /** + * Checks if the auto slide mode is currently on. + */ + function isAutoSliding() { + + return !!( autoSlide && !autoSlidePaused ); + + } + /** * Steps from the current point in the presentation to the * slide which matches the specified horizontal and vertical @@ -1465,11 +2099,11 @@ var Reveal = (function(){ previousSlide = currentSlide; // Query all horizontal slides in the deck - var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); + var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); // 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 ] ); } @@ -1519,9 +2153,9 @@ var Reveal = (function(){ 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 @@ -1558,13 +2192,14 @@ var Reveal = (function(){ // stacks if( previousSlide ) { previousSlide.classList.remove( 'present' ); + previousSlide.setAttribute( 'aria-hidden', 'true' ); // Reset all slides upon navigate to home // Issue: #285 - if ( document.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) { + if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) { // Launch async task setTimeout( function () { - var slides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i; + var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i; for( i in slides ) { if( slides[i] ) { // Reset stack @@ -1576,16 +2211,20 @@ var Reveal = (function(){ } // Handle embedded content - if( slideChanged ) { + if( slideChanged || !previousSlide ) { stopEmbeddedContent( previousSlide ); startEmbeddedContent( currentSlide ); } + // Announce the current slide contents, for screen readers + dom.statusDiv.textContent = currentSlide.textContent; + updateControls(); updateProgress(); updateBackground(); updateParallax(); updateSlideNumber(); + updateNotes(); // Update the URL hash writeURL(); @@ -1617,12 +2256,24 @@ var Reveal = (function(){ // Re-create the slide backgrounds createBackgrounds(); + // Write the current hash to the URL + writeURL(); + sortAllFragments(); updateControls(); updateProgress(); updateBackground( true ); updateSlideNumber(); + updateSlidesVisibility(); + updateNotes(); + + formatEmbeddedContent(); + startEmbeddedContent( currentSlide ); + + if( isOverview() ) { + layoutOverview(); + } } @@ -1632,7 +2283,7 @@ var Reveal = (function(){ */ function resetVerticalSlides() { - var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); + var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); @@ -1642,6 +2293,7 @@ var Reveal = (function(){ verticalSlide.classList.remove( 'present' ); verticalSlide.classList.remove( 'past' ); verticalSlide.classList.add( 'future' ); + verticalSlide.setAttribute( 'aria-hidden', 'true' ); } } ); @@ -1656,7 +2308,7 @@ var Reveal = (function(){ */ function sortAllFragments() { - var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); + var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); @@ -1672,6 +2324,23 @@ var Reveal = (function(){ } + /** + * 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. @@ -1689,9 +2358,11 @@ var Reveal = (function(){ // Select all slides and convert the NodeList result to // an array - var slides = toArray( document.querySelectorAll( selector ) ), + var slides = toArray( dom.wrapper.querySelectorAll( selector ) ), slidesLength = slides.length; + var printMode = isPrintingPDF(); + if( slidesLength ) { // Should the index loop? @@ -1717,43 +2388,55 @@ var Reveal = (function(){ // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute element.setAttribute( 'hidden', '' ); + element.setAttribute( 'aria-hidden', 'true' ); + + // If this element contains vertical slides + if( element.querySelector( 'section' ) ) { + element.classList.add( 'stack' ); + } + + // If we're printing static slides, all slides are "present" + if( printMode ) { + element.classList.add( 'present' ); + continue; + } if( i < index ) { // Any element previous to index is given the 'past' class element.classList.add( reverse ? 'future' : 'past' ); - var pastFragments = toArray( element.querySelectorAll( '.fragment' ) ); + if( config.fragments ) { + var pastFragments = toArray( element.querySelectorAll( '.fragment' ) ); - // Show all fragments on prior slides - while( pastFragments.length ) { - var pastFragment = pastFragments.pop(); - pastFragment.classList.add( 'visible' ); - pastFragment.classList.remove( 'current-fragment' ); + // Show all fragments on prior slides + while( pastFragments.length ) { + var pastFragment = pastFragments.pop(); + pastFragment.classList.add( 'visible' ); + pastFragment.classList.remove( 'current-fragment' ); + } } } else if( i > index ) { // Any element subsequent to index is given the 'future' class element.classList.add( reverse ? 'past' : 'future' ); - var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) ); + if( config.fragments ) { + var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) ); - // No fragments in future slides should be visible ahead of time - while( futureFragments.length ) { - var futureFragment = futureFragments.pop(); - futureFragment.classList.remove( 'visible' ); - futureFragment.classList.remove( 'current-fragment' ); + // No fragments in future slides should be visible ahead of time + while( futureFragments.length ) { + var futureFragment = futureFragments.pop(); + futureFragment.classList.remove( 'visible' ); + futureFragment.classList.remove( 'current-fragment' ); + } } } - - // If this element contains vertical slides - if( element.querySelector( 'section' ) ) { - element.classList.add( 'stack' ); - } } // Mark the current slide as present slides[index].classList.add( 'present' ); slides[index].removeAttribute( 'hidden' ); + slides[index].removeAttribute( 'aria-hidden' ); // If this slide has a state associated with it, add it // onto the current state of the deck @@ -1781,12 +2464,12 @@ var Reveal = (function(){ // Select all slides and convert the NodeList result to // an array - var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ), + var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ), horizontalSlidesLength = horizontalSlides.length, distanceX, distanceY; - if( horizontalSlidesLength ) { + if( horizontalSlidesLength && typeof indexh !== 'undefined' ) { // The number of steps away from the present slide that will // be visible @@ -1794,7 +2477,12 @@ var Reveal = (function(){ // Limit view distance on weaker devices if( isMobileDevice ) { - viewDistance = isOverview() ? 6 : 1; + viewDistance = isOverview() ? 6 : 2; + } + + // All slides need to be visible when exporting to PDF + if( isPrintingPDF() ) { + viewDistance = Number.MAX_VALUE; } for( var x = 0; x < horizontalSlidesLength; x++ ) { @@ -1803,11 +2491,22 @@ var Reveal = (function(){ 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 - 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 - horizontalSlide.style.display = distanceX > viewDistance ? 'none' : 'block'; + if( distanceX < viewDistance ) { + showSlide( horizontalSlide ); + } + else { + hideSlide( horizontalSlide ); + } if( verticalSlidesLength ) { @@ -1816,9 +2515,14 @@ var Reveal = (function(){ for( var y = 0; y < verticalSlidesLength; y++ ) { var verticalSlide = verticalSlides[y]; - distanceY = x === indexh ? Math.abs( indexv - y ) : Math.abs( y - oy ); + distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy ); - verticalSlide.style.display = ( distanceX + distanceY ) > viewDistance ? 'none' : 'block'; + if( distanceX + distanceY < viewDistance ) { + showSlide( verticalSlide ); + } + else { + hideSlide( verticalSlide ); + } } } @@ -1828,50 +2532,31 @@ var Reveal = (function(){ } + /** + * Pick up notes from the current slide and display tham + * to the viewer. + * + * @see `showNotes` config value + */ + 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 - if( config.progress && dom.progress ) { + if( config.progress && dom.progressbar ) { - var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); - - // The number of past and total slides - var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length; - var pastCount = 0; - - // Step through all slides and count the past ones - mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) { - - var horizontalSlide = horizontalSlides[i]; - var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); - - for( var j = 0; j < verticalSlides.length; j++ ) { - - // Stop as soon as we arrive at the present - if( verticalSlides[j].classList.contains( 'present' ) ) { - break mainLoop; - } - - pastCount++; - - } - - // Stop as soon as we arrive at the present - if( horizontalSlide.classList.contains( 'present' ) ) { - break; - } - - // Don't count the wrapping section for vertical slides - if( horizontalSlide.classList.contains( 'stack' ) === false ) { - pastCount++; - } - - } - - dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px'; + dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px'; } @@ -1879,19 +2564,60 @@ var Reveal = (function(){ /** * 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. + */ + function formatSlideNumber( a, delimiter, b ) { + + if( typeof b === 'number' && !isNaN( b ) ) { + return ''+ a +'' + + ''+ delimiter +'' + + ''+ b +''; + } + else { + return ''+ a +''; } } @@ -1912,34 +2638,37 @@ var Reveal = (function(){ .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' ); } ); } } @@ -1965,30 +2694,38 @@ var Reveal = (function(){ // states of their slides (past/present/future) toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) { + backgroundh.classList.remove( 'past' ); + backgroundh.classList.remove( 'present' ); + backgroundh.classList.remove( 'future' ); + if( h < indexh ) { - backgroundh.className = 'slide-background ' + horizontalPast; + backgroundh.classList.add( horizontalPast ); } else if ( h > indexh ) { - backgroundh.className = 'slide-background ' + horizontalFuture; + backgroundh.classList.add( horizontalFuture ); } else { - backgroundh.className = 'slide-background present'; + backgroundh.classList.add( 'present' ); // Store a reference to the current background element currentBackground = backgroundh; } if( includeAll || h === indexh ) { - toArray( backgroundh.childNodes ).forEach( function( backgroundv, v ) { + toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) { + + backgroundv.classList.remove( 'past' ); + backgroundv.classList.remove( 'present' ); + backgroundv.classList.remove( 'future' ); if( v < indexv ) { - backgroundv.className = 'slide-background past'; + backgroundv.classList.add( 'past' ); } else if ( v > indexv ) { - backgroundv.className = 'slide-background future'; + backgroundv.classList.add( 'future' ); } else { - backgroundv.className = 'slide-background present'; + backgroundv.classList.add( 'present' ); // Only if this is the present horizontal and vertical slide if( h === indexh ) currentBackground = backgroundv; @@ -1999,9 +2736,46 @@ var Reveal = (function(){ } ); - // Don't transition between identical backgrounds. This - // prevents unwanted flicker. + // Stop any currently playing video background + if( previousBackground ) { + + var previousVideo = previousBackground.querySelector( 'video' ); + if( previousVideo ) previousVideo.pause(); + + } + if( currentBackground ) { + + // Start video playback + var currentVideo = currentBackground.querySelector( 'video' ); + if( currentVideo ) { + + var startVideo = function() { + currentVideo.currentTime = 0; + currentVideo.play(); + currentVideo.removeEventListener( 'loadeddata', startVideo ); + }; + + if( currentVideo.readyState > 1 ) { + startVideo(); + } + else { + currentVideo.addEventListener( 'loadeddata', startVideo ); + } + + } + + 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; var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) { @@ -2009,6 +2783,20 @@ var Reveal = (function(){ } previousBackground = currentBackground; + + } + + // If there's a background brightness flag for this slide, + // bubble it to the .reveal container + if( currentSlide ) { + [ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) { + if( currentSlide.classList.contains( classToBubble ) ) { + dom.wrapper.classList.add( classToBubble ); + } + else { + dom.wrapper.classList.remove( classToBubble ); + } + } ); } // Allow the first background to apply without transition @@ -2026,8 +2814,8 @@ var Reveal = (function(){ if( config.parallaxBackgroundImage ) { - var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), - verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); + var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), + verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var backgroundSize = dom.background.style.backgroundSize.split( ' ' ), backgroundWidth, backgroundHeight; @@ -2040,16 +2828,143 @@ var Reveal = (function(){ 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 > 0 ? -( 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 * 1 : 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). + */ + function showSlide( slide ) { + + // Show the slide element + slide.style.display = 'block'; + + // Media elements with data-src attributes + 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 children + toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) { + var sources = 0; + + toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) { + source.setAttribute( 'src', source.getAttribute( 'data-src' ) ); + source.removeAttribute( 'data-src' ); + sources += 1; + } ); + + // If we rewrote sources for this video/audio element, we need + // to manually tell it to load from its new origin + if( sources > 0 ) { + media.load(); + } + } ); + + + // Show the corresponding background element + var indices = getIndices( slide ); + var background = getSlideBackground( indices.h, indices.v ); + if( background ) { + background.style.display = 'block'; + + // If the background contains media, load it + 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; + } + + // Support comma separated lists of video sources + backgroundVideo.split( ',' ).forEach( function( source ) { + video.innerHTML += ''; + } ); + + background.appendChild( video ); + } + // Iframes + else if( backgroundIframe ) { + var iframe = document.createElement( 'iframe' ); + iframe.setAttribute( 'src', backgroundIframe ); + 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. + */ + function hideSlide( slide ) { + + // Hide the slide element + slide.style.display = 'none'; + + // Hide the corresponding background element + var indices = getIndices( slide ); + var background = getSlideBackground( indices.h, indices.v ); + if( background ) { + background.style.display = 'none'; } } @@ -2061,8 +2976,8 @@ var Reveal = (function(){ */ function availableRoutes() { - var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), - verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); + var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), + verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var routes = { left: indexh > 0 || config.loop, @@ -2105,6 +3020,30 @@ var Reveal = (function(){ } + /** + * 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" + _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' ); + _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); + + // Vimeo frames must include "?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. @@ -2112,24 +3051,60 @@ var Reveal = (function(){ function startEmbeddedContent( slide ) { if( slide && !isSpeakerNotes() ) { + // Restart GIFs + toArray( slide.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' ) ) { + if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) { el.play(); } } ); - // iframe embeds - toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) { - el.contentWindow.postMessage( 'slide:start', '*' ); - }); + // Normal iframes + toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) { + startEmbeddedIframe( { target: el } ); + } ); - // 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":""}', '*' ); + // Lazy loading iframes + toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { + 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" the content of an embedded iframe using the + * postmessage API. + */ + function startEmbeddedIframe( event ) { + + var iframe = event.target; + + if( iframe && iframe.contentWindow ) { + + // YouTube postMessage API + if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { + iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); + } + // Vimeo postMessage API + else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { + iframe.contentWindow.postMessage( '{"method":"play"}', '*' ); + } + // Generic postMessage API + else { + iframe.contentWindow.postMessage( 'slide:start', '*' ); + } + } } @@ -2140,29 +3115,122 @@ var Reveal = (function(){ */ function stopEmbeddedContent( slide ) { - if( slide ) { + if( slide && slide.parentNode ) { // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { - if( !el.hasAttribute( 'data-ignore' ) ) { + if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) { el.pause(); } } ); - // iframe embeds + // Generic postMessage API for non-lazy loaded iframes toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) { el.contentWindow.postMessage( 'slide:stop', '*' ); + el.removeEventListener( 'load', startEmbeddedIframe ); }); - // YouTube embeds + // YouTube postMessage API toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); } }); + + // Vimeo postMessage API + toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) { + if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { + el.contentWindow.postMessage( '{"method":"pause"}', '*' ); + } + }); + + // Lazy loading iframes + toArray( slide.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 the number of past slides. This can be used as a global + * flattened index for slides. + */ + function getSlidePastCount() { + + var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); + + // 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++ ) { + + var horizontalSlide = horizontalSlides[i]; + var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); + + for( var j = 0; j < verticalSlides.length; j++ ) { + + // Stop as soon as we arrive at the present + if( verticalSlides[j].classList.contains( 'present' ) ) { + break mainLoop; + } + + pastCount++; + + } + + // Stop as soon as we arrive at the present + if( horizontalSlide.classList.contains( 'present' ) ) { + break; + } + + // Don't count the wrapping section for vertical slides + if( horizontalSlide.classList.contains( 'stack' ) === false ) { + pastCount++; + } + + } + + return pastCount; + + } + + /** + * Returns a value ranging from 0-1 that represents + * how far into the presentation we have navigated. + */ + 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 + // accounted for in the progress. + if( allFragments.length > 0 ) { + var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); + + // This value represents how big a portion of the slide progress + // that is made up by its fragments (0-1) + var fragmentWeight = 0.9; + + // Add fragment progress to the past slide count + pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight; + } + + } + + return pastCount / ( totalCount - 1 ); + + } + /** * Checks if this presentation is running inside of the * speaker notes window. @@ -2187,8 +3255,13 @@ var Reveal = (function(){ // If the first bit is invalid and there is a name we can // assume that this is a named link if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) { - // Find the slide with the specified name - var element = document.querySelector( '#' + name ); + 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.getElementById( name ); + } if( element ) { // Find the position of the named slide and navigate to it @@ -2230,12 +3303,18 @@ var Reveal = (function(){ if( typeof delay === 'number' ) { writeURLTimeout = setTimeout( writeURL, delay ); } - else { + else if( currentSlide ) { var url = '/'; + // Attempt to create a named link based on the slide's ID + var id = currentSlide.getAttribute( 'id' ); + if( id ) { + id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' ); + } + // If the current slide has an ID, use that as a named link - if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) { - url = '/' + currentSlide.getAttribute( 'id' ); + if( typeof id === 'string' && id.length ) { + url = '/' + id; } // Otherwise use the /h/v index else { @@ -2272,11 +3351,14 @@ var Reveal = (function(){ var slideh = isVertical ? slide.parentNode : slide; // Select all horizontal slides - var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); + var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // Now that we know which the horizontal slide is, get its index h = Math.max( horizontalSlides.indexOf( slideh ), 0 ); + // Assume we're not vertical + v = undefined; + // If this is a vertical slide, grab the vertical index if( isVertical ) { v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 ); @@ -2286,8 +3368,13 @@ var Reveal = (function(){ if( !slide && currentSlide ) { var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0; if( hasFragments ) { - var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); - f = visibleFragments.length - 1; + var currentFragment = currentSlide.querySelector( '.current-fragment' ); + if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) { + f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 ); + } + else { + f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1; + } } } @@ -2295,6 +3382,130 @@ var Reveal = (function(){ } + /** + * Retrieves the total number of slides in this presentation. + */ + function getTotalSlides() { + + return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length; + + } + + /** + * Returns the slide element matching the specified index. + */ + function getSlide( x, y ) { + + var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ]; + var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' ); + + if( verticalSlides && verticalSlides.length && typeof y === 'number' ) { + return verticalSlides ? verticalSlides[ y ] : undefined; + } + + return horizontalSlide; + + } + + /** + * 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. + */ + 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 ) { + return slide.slideBackgroundElement; + } + + return undefined; + } + + var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ]; + var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' ); + + if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) { + return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined; + } + + 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
+ * 2. As an