all files / src/ Grid.js

100% Statements 124/124
100% Branches 32/32
100% Functions 28/28
100% Lines 124/124
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309                  44× 44× 44× 44×                     36×       35× 35×   35× 35×   35× 35×   35× 35×   35×             43× 43× 43× 43× 43× 43×     43×   43× 101× 101×     43× 101× 101×   101×   101× 544×   101× 101×     43× 43× 43×                   43× 41×                           29× 29× 29× 29×   29×   29× 103×     29×   29× 103× 383×       29×   29× 383×     383×     29×                       26×               26×   26× 26×     26× 26×                   29× 27×                             31× 10× 10×     21× 21× 21× 21×             21× 21×   21× 293×     21× 293×     21× 21×   21× 21×                                                   41×     25× 25×   25×     16× 16×   16×             40×                          
/**
 * Implements the grid element and its internal manipulation features
 *
 * @param {Object} Grid
 * @param {String} Grid.columns  Stores the current number of columns
 * @param {Object} Grid.element  Stores the DOM object of the grid element
 * @param {Boolean} Grid.status  Pointer to maintain the Grid status
 * @constructor
 */
var Grid = function(element) {
  this.columns = null;
  this.element = element;
  this.filtered = document.createDocumentFragment();
  this.status = false;
};
 
/**
 * Set up the grid element and add columns
 *
 * @param  {Object}   options   Object containing configuration options.
 *                              Currently `columns` and `filter` are supported.
 * @param  {Function} callback  Optional. Callback function to call when done
 */
Grid.prototype.setup = function(options, callback) {
  // Run this only once on a grid.
  if (this.status) {
    return false;
  }
 
  // Retrieve the list of items from the grid itself.
  var range = document.createRange();
  var items = document.createElement('div');
 
  range.selectNodeContents(this.element);
  items.appendChild(range.extractContents());
 
  window.requestAnimationFrame(function() {
    addToDataset(items, 'columns', 0);
 
    this.addColumns(items, options);
    this.status = true;
 
    isFunction(callback) && callback.call(this);
  }.bind(this));
};
 
/**
 * Create columns with the configured classes and add a list of items to them.
 */
Grid.prototype.addColumns = function(items, options) {
  var columnClasses = ['column', 'size-1of'+ options.columns];
  var columnsFragment = document.createDocumentFragment();
  var columnsItems = [];
  var i = options.columns;
  var childSelector;
  var column, rowsFragment;
 
  // Filter out items when a filter is given.
  this.filterItems(items, options.filter);
 
  while (i-- !== 0) {
    childSelector = '[data-columns] > *:nth-child(' + options.columns + 'n-' + i + ')';
    columnsItems.push(items.querySelectorAll(childSelector));
  }
 
  each(columnsItems, function(rows) {
    column = document.createElement('div');
    rowsFragment = document.createDocumentFragment();
 
    column.className = columnClasses.join(' ');
 
    each(rows, function(row) {
      rowsFragment.appendChild(row);
    });
    column.appendChild(rowsFragment);
    columnsFragment.appendChild(column);
  });
 
  this.element.appendChild(columnsFragment);
  addToDataset(this.element, 'columns', options.columns);
  this.columns = options.columns;
};
 
/**
 * Filter items in a grid
 *
 * @param  {[type]} items  [description]
 * @param  {[type]} filter [description]
 * @return {[type]}        [description]
 */
Grid.prototype.filterItems = function(items, filter) {
  if (!filter) {
    return items;
  }
 
  var index, filtered, nodeList;
 
  nodeList = Array.prototype.slice.call(items.children);
  filtered = items.querySelectorAll('[data-columns] > ' + filter);
  each(filtered, function(item) {
    index = (nodeList.indexOf(item));
    this.filtered.appendChild(item);
    addToDataset(item, 'position', index);
  }, this);
 
  return items;
};
 
/**
 * Remove all the columns from a grid and prepare it for populating again.
 *
 * @param  Object grid The grid element object
 * @return Object      A list of items sorted by the ordering of columns
 */
Grid.prototype.removeColumns = function() {
  var range = document.createRange();
  var container = document.createElement('div');
  var sortedRows = [];
  var columns;
 
  range.selectNodeContents(this.element);
 
  columns = Array.prototype.filter.call(range.extractContents().childNodes, function filterElements(node) {
    return node instanceof window.HTMLElement;
  });
 
  sortedRows.length = columns[0].childNodes.length * columns.length;
 
  each(columns, function iterateColumns(column, columnIndex) {
    each(column.children, function iterateRows(row, rowIndex) {
      sortedRows[rowIndex * columns.length + columnIndex] = row;
    });
  });
 
  addToDataset(container, 'columns', 0);
 
  sortedRows.filter(function(child) {
    return !!child;
  })
  .forEach(function(child) {
    container.appendChild(child);
  });
 
  return container;
};
 
/**
 * Remove all the columns from the grid, and add them again if the number of
 * columns have changed.
 *
 * @param  {[type]}   newColumns The number of columns to transform the Grid
 *   element to.
 * @param  {Function} callback   Optional. Callback function to call when done
 * @return {[type]}              [description]
 */
Grid.prototype.redraw = function(newOptions, callback) {
  var evt = new CustomEvent('savvior:redraw', {
    detail: {
      element: this.element,
      from: this.columns,
      to: newOptions.columns,
      filter: newOptions.filter || null
    }
  });
  var items;
 
  window.requestAnimationFrame(function() {
    if (this.columns !== newOptions.columns) {
      items = this.restoreFiltered(this.removeColumns());
      this.addColumns(items, newOptions);
    }
 
    window.dispatchEvent(evt);
    isFunction(callback) && callback(this);
  }.bind(this));
};
 
/**
 * Restore filtered items in a grid
 *
 * @param  {[type]} container [description]
 * @return {[type]}           [description]
 */
Grid.prototype.restoreFiltered = function(container) {
  if (this.filtered.childNodes.length === 0) {
    return container;
  }
 
  var allItems = container;
  var pos;
 
  each(this.filtered.querySelectorAll('[data-position]'), function(item) {
    pos = Number(item.getAttribute('data-position'));
    item.removeAttribute('data-position');
    // Insert the element back to its original position. ReferenceNode is now
    // set to null if the element should become the last one.
    allItems.insertBefore(item, (allItems.children[pos] || null));
  });
 
  return container;
};
 
/**
 * Restore the Grid element to its original state
 *
 * @param  {Function} callback  Optional. Callback function to call when done
 */
Grid.prototype.restore = function(callback, scope) {
  if (!this.status) {
    isFunction(callback) && callback(false);
    return false;
  }
 
  var fragment = document.createDocumentFragment();
  var children = [];
  var container;
  var evt = new CustomEvent('savvior:restore', {
    detail: {
      element: this.element,
      from: this.columns
    }
  });
 
  window.requestAnimationFrame(function() {
    container = this.restoreFiltered(this.removeColumns());
 
    each(container.childNodes, function(item) {
      children.push(item);
    });
 
    children.forEach(function(child) {
      fragment.appendChild(child);
    });
 
    this.element.appendChild(fragment);
    this.element.removeAttribute('data-columns');
 
    window.dispatchEvent(evt);
    isFunction(callback) && callback.call(scope, scope || this);
  }.bind(this));
};
 
/**
 * Add items to a Grid.
 *
 * This triggers the event 'savvior:addItems' with the following object in
 * Event.detail:
 *   - element: the Grid instance element
 *   - grid: the Grid instance
 *
 * @param  {Mixed}   elements  A Node, array of Nodes or a NodeList representing
 *   the elements to add to the Grid.
 * @param  {Bool}    clone     Set this to true when the elements need copying,
 *   not moving. Optional.
 * @param  {Function} callback Callback function to execute after the
 *   elements are appended. The callback is called with the Grid instance.
 *   Optional.
 * @return {Grid}              Grid instance.
 */
Grid.prototype.addItems = function (elements, options, callback) {
  var evt = new CustomEvent('savvior:addItems', {
    detail: {
      element: this.element,
      grid: this
    }
  });
  var prepareElement = function(el) {
    return options.clone ? el.cloneNode(true) : el;
  };
  var methods = {
    append: function (el, items) {
      var newEl = prepareElement(el);
      items.appendChild(newEl);
 
      return items;
    },
    prepend: function (el, items) {
      var newEl = prepareElement(el);
      items.insertBefore(newEl, items.firstChild);
 
      return items;
    }
  };
 
  window.requestAnimationFrame(function () {
    // Reset the container, restoring any previously filtered items.
    var items = this.restoreFiltered(this.removeColumns());
 
    // If new elements is a NodeList or an array of Nodes, append each to items.
    if (elements instanceof NodeList || elements instanceof Array) {
      each(elements, function (el) {
        items = methods[options.method].call(null, el, items);
      });
    }
    else {
      items = methods[options.method].call(null, elements, items);
    }
 
    this.addColumns(items, {
      columns: this.columns,
      filter: this.filter
    });
 
    window.dispatchEvent(evt);
    isFunction(callback) && callback(this);
  }.bind(this));
 
};