Skip to content

Commit bc07073

Browse files
committed
Use sessionStorage to avoid flash of loading zero counts
1 parent 090fb5d commit bc07073

File tree

1 file changed

+23
-6
lines changed
  • assets/src/amp-validation/counts

1 file changed

+23
-6
lines changed

assets/src/amp-validation/counts/index.js

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ import domReady from '@wordpress/dom-ready';
1010
*/
1111
import './style.css';
1212

13+
/**
14+
* Get session storage key for storing the previously-fetched count.
15+
*
16+
* @param {string} itemId Menu item ID.
17+
* @return {string} Session storage key.
18+
*/
19+
function getSessionStorageKey( itemId ) {
20+
return `${ itemId }-last-count`;
21+
}
22+
1323
/**
1424
* Sets the loading state on a menu item.
1525
*
@@ -22,12 +32,15 @@ function setMenuItemIsLoading( itemId ) {
2232
return;
2333
}
2434

25-
const loadingEl = document.createElement( 'span' );
35+
// Add a loading spinner if we haven't obtained the count before or the last count was not zero.
36+
const lastCount = sessionStorage.getItem( getSessionStorageKey( itemId ) );
37+
if ( ! lastCount || '0' !== lastCount ) {
38+
const loadingEl = document.createElement( 'span' );
39+
loadingEl.classList.add( 'amp-count-loading' );
40+
itemEl.append( loadingEl );
2641

27-
loadingEl.classList.add( 'amp-count-loading' );
28-
itemEl.classList.add( 'awaiting-mod' );
29-
30-
itemEl.append( loadingEl );
42+
itemEl.classList.add( 'awaiting-mod' );
43+
}
3144
}
3245

3346
/**
@@ -48,8 +61,12 @@ function setMenuItemCountValue( itemId, count ) {
4861

4962
if ( isNaN( count ) || count === 0 ) {
5063
itemEl.parentNode.removeChild( itemEl );
64+
sessionStorage.setItem( getSessionStorageKey( itemId ), '0' );
5165
} else {
52-
itemEl.textContent = count.toLocaleString();
66+
const text = count.toLocaleString();
67+
itemEl.textContent = text;
68+
itemEl.classList.add( 'awaiting-mod' ); // In case it wasn't set in setMenuItemIsLoading().
69+
sessionStorage.setItem( getSessionStorageKey( itemId ), text );
5370
}
5471
}
5572

0 commit comments

Comments
 (0)