Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A grid vm for Mithril
'use strict';
function grid( axis ){
var items = [];
var pending;
var container;
function queue(){
if( pending ) ( window.cancelAnimationFrame || window.clearTimeout )( pending );
pending = ( window.requestAnimationFrame || window.setTimeout )( apply, 16 );
}
function apply(){
var total = container.clientWidth;
var occupied = items.reduce( function( accumulator, item, index ){
return accumulator + ( item.shouldExpand ? 0 : item.el.clientWidth );
}, 0 );
var remaining = total - occupied;
if( remaining < 0 ){
items.forEach( function equalize( item ){
item.el.style.width = total / items.length + 'px';
} );
}
else {
items
.filter( function shouldEpand( item ){
return item.shouldExpand;
} )
.forEach( function distribute( item, index, array ){
item.el.style.width = remaining / array.length + 'px';
} );
}
}
function setup(){
window.addEventListener( 'resize', apply, false );
}
function teardown(){
window.removeEventListener( 'resize', apply, false );
}
return {
container : function registerContainer( axis ){
items = [];
return function config( el, init, context ){
if( !init ){
container = el;
setup();
context.onunload = teardown;
}
queue();
};
},
item : function registerItem( shouldExpand ){
var item = {
shouldExpand : shouldExpand
};
var index = items.push( item );
return function config( el, init, context ){
if( !init ){
item.el = el;
context.unload = function unregister(){
items.splice( items.indexOf( item ), index, 1 );
};
}
};
}
};
}
module.exports = grid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.