« MediaWiki:Common.js » : différence entre les versions
Page de l’interface de MediaWiki
Autres actions
m Minicard |
minicard |
||
| Ligne 259 : | Ligne 259 : | ||
'use strict'; | 'use strict'; | ||
var MIN_CARD_WIDTH = 140; | var MIN_CARD_WIDTH = 140; | ||
var GAP = 12; | var GAP = 12; | ||
function | function calcBestCols( total, containerWidth ) { | ||
var maxColsByWidth = Math.floor( | |||
( containerWidth + GAP ) / ( MIN_CARD_WIDTH + GAP ) | |||
); | |||
maxColsByWidth = Math.max( 1, Math.min( maxColsByWidth, total ) ); | |||
/* Cherche le diviseur exact le plus grand <= maxColsByWidth */ | |||
var bestCols = 1; | |||
for ( var n = 1; n <= maxColsByWidth; n++ ) { | |||
if ( total % n === 0 ) { | |||
bestCols = n; | |||
} | |||
} | |||
/* Pas de diviseur exact : on prend maxColsByWidth */ | |||
if ( bestCols === 1 && maxColsByWidth > 1 ) { | |||
bestCols = maxColsByWidth; | |||
} | |||
return bestCols; | |||
} | |||
function adjustGrid( grid ) { | |||
var cards = grid.querySelectorAll( '.minicard' ); | |||
var total = cards.length; | |||
if ( total === 0 ) return; | |||
var containerWidth = grid.offsetWidth; | |||
/* Si le conteneur n'est pas encore rendu (width = 0), on réessaie */ | |||
if ( containerWidth === 0 ) { | |||
requestAnimationFrame( function () { adjustGrid( grid ); } ); | |||
} | return; | ||
} | |||
var bestCols = calcBestCols( total, containerWidth ); | |||
grid.style.gridTemplateColumns = 'repeat(' + bestCols + ', 1fr)'; | |||
/* Hauteur adaptative */ | |||
var cardWidth = ( containerWidth - ( bestCols - 1 ) * GAP ) / bestCols; | |||
var rowHeight = cardWidth < 120 ? '48px' : cardWidth < 160 ? '52px' : '60px'; | |||
grid.style.gridAutoRows = rowHeight; | |||
cards.forEach( function ( c ) { | |||
c.style.height = rowHeight; | |||
} ); | } ); | ||
/* Révèle la grille une fois calculée */ | |||
grid.classList.add( 'is-ready' ); | |||
} | } | ||
function adjustAllGrids() { | |||
function | document.querySelectorAll( '.minicard-grid' ).forEach( adjustGrid ); | ||
} | } | ||
/* Exécution immédiate si le DOM est prêt, sinon au plus tôt */ | |||
if ( document.readyState === 'loading' ) { | if ( document.readyState === 'loading' ) { | ||
document.addEventListener( 'DOMContentLoaded', | document.addEventListener( 'DOMContentLoaded', adjustAllGrids ); | ||
} else { | } else { | ||
adjustAllGrids(); | |||
} | } | ||
window.addEventListener( 'resize', | /* Recalcul au resize avec debounce */ | ||
var resizeTimer; | |||
window.addEventListener( 'resize', function () { | |||
clearTimeout( resizeTimer ); | |||
resizeTimer = setTimeout( adjustAllGrids, 100 ); | |||
} ); | |||
}() ); | }() ); | ||