Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created November 13, 2014 19:50
Show Gist options
  • Select an option

  • Save barneycarroll/efd0c8768dc9813ce656 to your computer and use it in GitHub Desktop.

Select an option

Save barneycarroll/efd0c8768dc9813ce656 to your computer and use it in GitHub Desktop.

Revisions

  1. barneycarroll created this gist Nov 13, 2014.
    80 changes: 80 additions & 0 deletions grid.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    '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;