Browse Source

add data-fragment=<index> attribute to slide <sections>

Hakim El Hattab 5 years ago
parent
commit
ac50753521
2 changed files with 27 additions and 0 deletions
  1. 11 0
      js/reveal.js
  2. 16 0
      test/test.js

+ 11 - 0
js/reveal.js

@@ -4751,6 +4751,8 @@
 
 			if( fragments.length ) {
 
+				var maxIndex = 0;
+
 				if( typeof index !== 'number' ) {
 					var currentFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
 					if( currentFragment ) {
@@ -4764,6 +4766,8 @@
 						i = parseInt( el.getAttribute( 'data-fragment-index' ), 10 );
 					}
 
+					maxIndex = Math.max( maxIndex, i );
+
 					// Visible fragments
 					if( i <= index ) {
 						if( !el.classList.contains( 'visible' ) ) changedFragments.shown.push( el );
@@ -4787,6 +4791,13 @@
 
 				} );
 
+				// Write the current fragment index to the slide <section>.
+				// This can be used by end users to apply styles based on
+				// the current fragment index.
+				index = typeof index === 'number' ? index : -1;
+				index = Math.max( Math.min( index, maxIndex ), -1 );
+				currentSlide.setAttribute( 'data-fragment', index );
+
 			}
 
 		}

+ 16 - 0
test/test.js

@@ -250,6 +250,22 @@ Reveal.addEventListener( 'ready', function() {
 		assert.deepEqual( Reveal.getIndices(), { h: 2, v: 0, f: 1 }, 'Reveal.slide( 2, 0, 1 )' );
 	});
 
+	QUnit.test( 'data-fragment is set on slide <section>', function( assert ) {
+		Reveal.slide( 2, 0, -1 );
+		assert.deepEqual( Reveal.getCurrentSlide().getAttribute( 'data-fragment' ), '-1' );
+
+		Reveal.slide( 2, 0, 2 );
+		assert.deepEqual( Reveal.getCurrentSlide().getAttribute( 'data-fragment' ), '2' );
+
+		Reveal.slide( 2, 0, 0 );
+		assert.deepEqual( Reveal.getCurrentSlide().getAttribute( 'data-fragment' ), '0' );
+
+		var fragmentSlide = Reveal.getCurrentSlide();
+
+		Reveal.slide( 3, 0 );
+		assert.deepEqual( fragmentSlide.getAttribute( 'data-fragment' ), '0', 'data-fragment persists when jumping to another slide' );
+	});
+
 	QUnit.test( 'Hiding all fragments', function( assert ) {
 		var fragmentSlide = document.querySelector( '#fragment-slides>section:nth-child(1)' );