<commit_before>
var SaikuTableRenderer = _.extend(SaikuRenderer, {

    key: "table",
});

SaikuTableRenderer.prototype._render = function(data, options) {
        var self = this;
        if (data) {
            this._data = data;
        }
        if (options) {
            this._options = _.extend({}, SaikuRendererOptions, options);
        }

        if (typeof this._data == "undefined") {
            return;
        }

        if (this._data != null && this._data.error != null) {
            return;
        }
        if (this._data == null || (this._data.cellset && this._data.cellset.length === 0)) {
            return;
        }
        if (this._options.htmlObject) {
            // in case we have some left over scrollers
            $(self._options.htmlObject).parent().parent().unbind('scroll');

            _.defer(function(that) {
                var html =  self.internalRender(self._data.cellset, self._options);
                $(self._options.htmlObject).html(html);
                _.defer(function(that) {
                    if (self._options.batch && self._options.hasBatchResult) {
                        var batchRow = 0;
                        var batchIsRunning = false;
                        var batchIntervalSize = self._options.hasOwnProperty('batchIntervalSize') ? self._options.batchIntervalSize : 10;
                        var batchIntervalTime = self._options.hasOwnProperty('batchIntervalTime') ? self._options.batchIntervalTime : 10;

                        var len = self._options.batchResult.length;

                        var batchInsert = function() {
                            // maybe add check for reach table bottom - ($('.workspace_results').scrollTop() , $('.workspace_results table').height()
                            if (!batchIsRunning && len > 0 && batchRow < len) {
                                batchIsRunning = true;
                                var batchContent = "";
                                var startb = batchRow;
                                for (var i = 0;  batchRow < len && i < batchIntervalSize ; i++, batchRow++) {
                                    batchContent += self._options.batchResult[batchRow];
                                }
                                if (batchRow > startb) {
                                    $(self._options.htmlObject).append( $(batchContent));
                                }
                                batchIsRunning = false;
                            }
                            if (batchRow >= len) {
                                $(self._options.htmlObject).parent().parent().unbind('scroll');
                            }
                        };

                        var lazyBatchInsert = _.debounce(batchInsert, batchIntervalTime);
                        $(self._options.htmlObject).parent().parent().scroll(function () {
                            lazyBatchInsert();
                        });
                    }
                });
                return html;
            });
        } else {
            var html =  this.internalRender(this._data.cellset, self._options);
            return html;
        }

};

SaikuTableRenderer.prototype.clear = function(data, options) {
    var self = this;
    if (this._options.htmlObject) {
        $(self._options.htmlObject).parent().parent().unbind('scroll');
    }

};

SaikuTableRenderer.prototype._processData = function(data, options) {
    this._hasProcessed = true;
};

function nextParentsDiffer(data, row, col) {
    while (row-- > 0) {
        if (data[row][col].properties.uniquename != data[row][col + 1].properties.uniquename)
            return true;
    }
    return false;
}

SaikuTableRenderer.prototype.internalRender = function(data, options) {
    var tableContent = "";
    var rowContent = "";

    var table = data ? data : [];
    var colSpan;
    var colValue;
    var isHeaderLowestLvl;
    var isBody = false;
    var firstColumn;
    var isLastColumn, isLastRow;
    var nextHeader;
    var processedRowHeader = false;
    var lowestRowLvl = 0;
    var rowGroups = [];
    var batchSize = null;
    var batchStarted = false;
    var resultRows = [];
    if (options) {
        batchSize = options.hasOwnProperty('batchSize') ? options.batchSize : null;
    }

    for (var row = 0, rowLen = table.length; row < rowLen; row++) {
        colSpan = 1;
        colValue = "";
        isHeaderLowestLvl = false;
        isLastColumn = false;
        isLastRow = false;
        var headerSame = false;
        rowContent = "
";
        for (var col = 0, colLen = table[row].length; col < colLen; col++) {
            var header = data[row][col];

            // If the cell is a column header and is null (top left of table)
            if (header.type === "COLUMN_HEADER" && header.value === "null" && (firstColumn == null || col < firstColumn)) {
                rowContent += '

	';
            } // If the cell is a column header and isn't null (column header of table)
            else if (header.type === "COLUMN_HEADER") {
                if (firstColumn == null) {
                    firstColumn = col;
                }
                if (table[row].length == col+1)
                    isLastColumn = true;
                else
                    nextHeader = data[row][col+1];

                if (isLastColumn) {
                    // Last column in a row...
                    if (header.value == "null") {
                        rowContent += '

	';
                    } else {
                        rowContent += '
' + header.value + '
	';
                    }

                } else {
                    // All the rest...
                    var groupChange = (col > 1 && row > 1 && !isHeaderLowestLvl && col > firstColumn) ?
                        data[row-1][col+1].value != data[row-1][col].value || data[row-1][col+1].properties.uniquename != data[row-1][col].properties.uniquename
                        : false;

                    var maxColspan = colSpan > 999 ? true : false;
                    if (header.value != nextHeader.value || nextParentsDiffer(data, row, col) || header.properties.uniquename != nextHeader.properties.uniquename || isHeaderLowestLvl || groupChange || maxColspan) {
                        if (header.value == "null") {
                            rowContent += '

	';
                        } else {
                            rowContent += '
' + header.value + '
	';
                        }
                        colSpan = 1;
                    } else {
                        colSpan++;
                    }
                }
            } // If the cell is a row header and is null (grouped row header)
            else if (header.type === "ROW_HEADER" && header.value === "null") {
                rowContent += '

	';
            } // If the cell is a row header and isn't null (last row header)
            else if (header.type === "ROW_HEADER") {
                if (lowestRowLvl == col)
                    isHeaderLowestLvl = true;
                else
                    nextHeader = data[row][col+1];

                var previousRow = data[row - 1];

                var same = !headerSame && !isHeaderLowestLvl && (col == 0 || previousRow[col-1].properties.uniquename == data[row][col-1].properties.uniquename) && header.properties.uniquename === previousRow[col].properties.uniquename;
                headerSame = !same;
                var value = (same ? "

" : '
' + header.value + '
');
                var tipsy = "";
                /* var tipsy = ' original-title="';
                if (!same && header.metaproperties) {
                    for (key in header.metaproperties) {
                        if (key.substring(0,1) != "$" && key.substring(1,2).toUpperCase() != key.substring(1,2)) {
                            tipsy += "" + safe_tags_replace(key) + " : " + safe_tags_replace(header.metaproperties[key]) + "
";
                        }
                    }
                }
                tipsy += '"';
                */
                var cssclass = (same ? "row_null" : "row");
                var colspan = 0;

                if (!isHeaderLowestLvl && (typeof nextHeader == "undefined" || nextHeader.value === "null")) {
                    colspan = 1;
                    var group = header.properties.dimension;
                    var level = header.properties.level;
                    var groupWidth = (group in rowGroups ? rowGroups[group].length - rowGroups[group].indexOf(level) : 1);
                    for (var k = col + 1; colspan < groupWidth && k <= (lowestRowLvl+1) && data[row][k] !== "null"; k++) {
                        colspan = k - col;
                    }
                    col = col + colspan -1;
                }
                rowContent += ' 0 ? ' colspan="' + colspan + '"' : "") + tipsy + '>' + value + '	';
            }
            else if (header.type === "ROW_HEADER_HEADER") {
                rowContent += '
' + header.value + '
	';
                isHeaderLowestLvl = true;
                processedRowHeader = true;
                lowestRowLvl = col;
                if (header.properties.hasOwnProperty("dimension")) {
                    var group = header.properties.dimension;
                    if (!(group in rowGroups)) {
                        rowGroups[group] = [];
                    }
                    rowGroups[group].push(header.properties.level);
                }
            } // If the cell is a normal data cell
            else if (header.type === "DATA_CELL") {
                batchStarted = true;
                var color = "";
                var val = header.value;
                var arrow = "";
                if (header.properties.hasOwnProperty('image')) {
                    var img_height = header.properties.hasOwnProperty('image_height') ? " height='" + header.properties.image_height + "'" : "";
                    var img_width = header.properties.hasOwnProperty('image_width') ? " width='" + header.properties.image_width + "'" : "";
                    val = "";
                }

                if (header.properties.hasOwnProperty('style')) {
                    color = " style='background-color: " + header.properties.style + "' ";
                }
                if (header.properties.hasOwnProperty('link')) {
                    val = "" + val + "";
                }
                if (header.properties.hasOwnProperty('arrow')) {
                    arrow = "";
                }

                rowContent += '
' + val + arrow + '
	';
            }
        }
        rowContent += "
";
        if (batchStarted && batchSize) {
                if (row <= batchSize) {
                    tableContent += rowContent;
                } else {
                    resultRows.push(rowContent);
                }
        } else {
            tableContent += rowContent;
        }

    }
    if (options) {
        options['batchResult'] = resultRows;
        options['hasBatchResult'] = resultRows.length > 0;
    }
    return "
" + tableContent + "
";
}<commit_msg>add better default handling for batch size<commit_after>
var SaikuTableRenderer = _.extend(SaikuRenderer, {

    key: "table",
});

SaikuTableRenderer.prototype._render = function(data, options) {
        var self = this;
        if (data) {
            this._data = data;
        }
        if (options) {
            this._options = _.extend({}, SaikuRendererOptions, options);
        }

        if (typeof this._data == "undefined") {
            return;
        }

        if (this._data != null && this._data.error != null) {
            return;
        }
        if (this._data == null || (this._data.cellset && this._data.cellset.length === 0)) {
            return;
        }
        if (this._options.htmlObject) {
            // in case we have some left over scrollers
            $(self._options.htmlObject).parent().parent().unbind('scroll');

            _.defer(function(that) {
                if (self._options.hasOwnProperty('batch') && !self._options.hasOwnProperty('batchSize')) {
                    self._options['batchSize'] = 1000;
                }

                var html =  self.internalRender(self._data.cellset, self._options);
                $(self._options.htmlObject).html(html);
                _.defer(function(that) {
                    if (self._options.hasOwnProperty('batch') && self._options.hasBatchResult) {
                        var batchRow = 0;
                        var batchIsRunning = false;
                        var batchIntervalSize = self._options.hasOwnProperty('batchIntervalSize') ? self._options.batchIntervalSize : 20;
                        var batchIntervalTime = self._options.hasOwnProperty('batchIntervalTime') ? self._options.batchIntervalTime : 20;

                        var len = self._options.batchResult.length;

                        var batchInsert = function() {
                            // maybe add check for reach table bottom - ($('.workspace_results').scrollTop() , $('.workspace_results table').height()
                            if (!batchIsRunning && len > 0 && batchRow < len) {
                                batchIsRunning = true;
                                var batchContent = "";
                                var startb = batchRow;
                                for (var i = 0;  batchRow < len && i < batchIntervalSize ; i++, batchRow++) {
                                    batchContent += self._options.batchResult[batchRow];
                                }
                                if (batchRow > startb) {
                                    $(self._options.htmlObject).append( $(batchContent));
                                }
                                batchIsRunning = false;
                            }
                            if (batchRow >= len) {
                                $(self._options.htmlObject).parent().parent().unbind('scroll');
                            }
                        };

                        var lazyBatchInsert = _.debounce(batchInsert, batchIntervalTime);
                        $(self._options.htmlObject).parent().parent().scroll(function () {
                            lazyBatchInsert();
                        });
                    }
                });
                return html;
            });
        } else {
            var html =  this.internalRender(this._data.cellset, self._options);
            return html;
        }

};

SaikuTableRenderer.prototype.clear = function(data, options) {
    var self = this;
    if (this._options.htmlObject) {
        $(self._options.htmlObject).parent().parent().unbind('scroll');
    }

};

SaikuTableRenderer.prototype._processData = function(data, options) {
    this._hasProcessed = true;
};

function nextParentsDiffer(data, row, col) {
    while (row-- > 0) {
        if (data[row][col].properties.uniquename != data[row][col + 1].properties.uniquename)
            return true;
    }
    return false;
}

SaikuTableRenderer.prototype.internalRender = function(data, options) {
    var tableContent = "";
    var rowContent = "";

    var table = data ? data : [];
    var colSpan;
    var colValue;
    var isHeaderLowestLvl;
    var isBody = false;
    var firstColumn;
    var isLastColumn, isLastRow;
    var nextHeader;
    var processedRowHeader = false;
    var lowestRowLvl = 0;
    var rowGroups = [];
    var batchSize = null;
    var batchStarted = false;
    var resultRows = [];
    if (options) {
        batchSize = options.hasOwnProperty('batchSize') ? options.batchSize : null;
    }

    for (var row = 0, rowLen = table.length; row < rowLen; row++) {
        colSpan = 1;
        colValue = "";
        isHeaderLowestLvl = false;
        isLastColumn = false;
        isLastRow = false;
        var headerSame = false;
        rowContent = "
";
        for (var col = 0, colLen = table[row].length; col < colLen; col++) {
            var header = data[row][col];

            // If the cell is a column header and is null (top left of table)
            if (header.type === "COLUMN_HEADER" && header.value === "null" && (firstColumn == null || col < firstColumn)) {
                rowContent += '

	';
            } // If the cell is a column header and isn't null (column header of table)
            else if (header.type === "COLUMN_HEADER") {
                if (firstColumn == null) {
                    firstColumn = col;
                }
                if (table[row].length == col+1)
                    isLastColumn = true;
                else
                    nextHeader = data[row][col+1];

                if (isLastColumn) {
                    // Last column in a row...
                    if (header.value == "null") {
                        rowContent += '

	';
                    } else {
                        rowContent += '
' + header.value + '
	';
                    }

                } else {
                    // All the rest...
                    var groupChange = (col > 1 && row > 1 && !isHeaderLowestLvl && col > firstColumn) ?
                        data[row-1][col+1].value != data[row-1][col].value || data[row-1][col+1].properties.uniquename != data[row-1][col].properties.uniquename
                        : false;

                    var maxColspan = colSpan > 999 ? true : false;
                    if (header.value != nextHeader.value || nextParentsDiffer(data, row, col) || header.properties.uniquename != nextHeader.properties.uniquename || isHeaderLowestLvl || groupChange || maxColspan) {
                        if (header.value == "null") {
                            rowContent += '

	';
                        } else {
                            rowContent += '
' + header.value + '
	';
                        }
                        colSpan = 1;
                    } else {
                        colSpan++;
                    }
                }
            } // If the cell is a row header and is null (grouped row header)
            else if (header.type === "ROW_HEADER" && header.value === "null") {
                rowContent += '

	';
            } // If the cell is a row header and isn't null (last row header)
            else if (header.type === "ROW_HEADER") {
                if (lowestRowLvl == col)
                    isHeaderLowestLvl = true;
                else
                    nextHeader = data[row][col+1];

                var previousRow = data[row - 1];

                var same = !headerSame && !isHeaderLowestLvl && (col == 0 || previousRow[col-1].properties.uniquename == data[row][col-1].properties.uniquename) && header.properties.uniquename === previousRow[col].properties.uniquename;
                headerSame = !same;
                var value = (same ? "

" : '
' + header.value + '
');
                var tipsy = "";
                /* var tipsy = ' original-title="';
                if (!same && header.metaproperties) {
                    for (key in header.metaproperties) {
                        if (key.substring(0,1) != "$" && key.substring(1,2).toUpperCase() != key.substring(1,2)) {
                            tipsy += "" + safe_tags_replace(key) + " : " + safe_tags_replace(header.metaproperties[key]) + "
";
                        }
                    }
                }
                tipsy += '"';
                */
                var cssclass = (same ? "row_null" : "row");
                var colspan = 0;

                if (!isHeaderLowestLvl && (typeof nextHeader == "undefined" || nextHeader.value === "null")) {
                    colspan = 1;
                    var group = header.properties.dimension;
                    var level = header.properties.level;
                    var groupWidth = (group in rowGroups ? rowGroups[group].length - rowGroups[group].indexOf(level) : 1);
                    for (var k = col + 1; colspan < groupWidth && k <= (lowestRowLvl+1) && data[row][k] !== "null"; k++) {
                        colspan = k - col;
                    }
                    col = col + colspan -1;
                }
                rowContent += ' 0 ? ' colspan="' + colspan + '"' : "") + tipsy + '>' + value + '	';
            }
            else if (header.type === "ROW_HEADER_HEADER") {
                rowContent += '
' + header.value + '
	';
                isHeaderLowestLvl = true;
                processedRowHeader = true;
                lowestRowLvl = col;
                if (header.properties.hasOwnProperty("dimension")) {
                    var group = header.properties.dimension;
                    if (!(group in rowGroups)) {
                        rowGroups[group] = [];
                    }
                    rowGroups[group].push(header.properties.level);
                }
            } // If the cell is a normal data cell
            else if (header.type === "DATA_CELL") {
                batchStarted = true;
                var color = "";
                var val = header.value;
                var arrow = "";
                if (header.properties.hasOwnProperty('image')) {
                    var img_height = header.properties.hasOwnProperty('image_height') ? " height='" + header.properties.image_height + "'" : "";
                    var img_width = header.properties.hasOwnProperty('image_width') ? " width='" + header.properties.image_width + "'" : "";
                    val = "";
                }

                if (header.properties.hasOwnProperty('style')) {
                    color = " style='background-color: " + header.properties.style + "' ";
                }
                if (header.properties.hasOwnProperty('link')) {
                    val = "" + val + "";
                }
                if (header.properties.hasOwnProperty('arrow')) {
                    arrow = "";
                }

                rowContent += '
' + val + arrow + '
	';
            }
        }
        rowContent += "
";
        if (batchStarted && batchSize) {
                if (row <= batchSize) {
                    tableContent += rowContent;
                } else {
                    resultRows.push(rowContent);
                }
        } else {
            tableContent += rowContent;
        }

    }
    if (options) {
        options['batchResult'] = resultRows;
        options['hasBatchResult'] = resultRows.length > 0;
    }
    return "
" + tableContent + "
";
}<|endoftext|>


<commit_before>'use strict';

var check = require('./check');

describe('lost-masonry-column', function() {
  describe('Custom Gutter', function() {
    it('supports a custom gutter', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-gutter: 20px; }',
        'a { float: left; width: calc(99.9% * 60px - 20px); margin-left: 10px;' +
        ' margin-right: 10px; }'
      );
    });

    it('supports no gutter', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-gutter: 0px; }',
        'a { float: left; width: calc(99.9% * 60px - 0px); margin-left: 0;' +
        ' margin-right: 0; }'
      );
    });

    it('supports a null unit for "no gutter"', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-gutter: 0; }',
        'a { float: left; width: calc(99.9% * 60px); margin-left: 0;' +
        ' margin-right: 0; }'
      );
    });
  });

  describe('flexbox', function() {
    it('supports flexbox with long-form property', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-flexbox: flex; }',
        'a { flex: 0 0 auto; width: calc(99.9% * 60px - 30px);' +
        ' margin-left: 15px; margin-right: 15px; }'
      )
    });

    it('supports a custom gutter', function() {
      check(
        'a { lost-masonry-column: 60px flex; }',
        'a { flex: 0 0 auto; width: calc(99.9% * 60px - 30px);' +
        ' margin-left: 15px; margin-right: 15px; }'
      );
    });

    it('supports no gutter', function() {
      check(
        'a { lost-masonry-column: 0 flex; }',
        'a { flex: 0 0 auto; width: calc(99.9% * 0 - 30px);' +
        ' margin-left: 15px; margin-right: 15px; }'
      );
    });
  });

  describe('allows for customizable rounders', function() {
    it('100%', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-rounder: 99.99999999999; }',
        'a { float: left; width: calc(99.99999999999% * 60px - 30px); margin-left: 15px;' +
        ' margin-right: 15px; }'
      );
    });

    it('99.99999999999%', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-rounder: 100; }',
        'a { float: left; width: calc(100% * 60px - 30px); margin-left: 15px;' +
        ' margin-right: 15px; }'
      );
    });
  });
});
<commit_msg>Adds tests for non-flexbox usage<commit_after>'use strict';

var check = require('./check');

describe('lost-masonry-column', function() {
  describe('Custom Gutter', function() {
    it('supports a custom gutter', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-gutter: 20px; }',
        'a { float: left; width: calc(99.9% * 60px - 20px); margin-left: 10px;' +
        ' margin-right: 10px; }'
      );
    });

    it('supports no gutter', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-gutter: 0px; }',
        'a { float: left; width: calc(99.9% * 60px - 0px); margin-left: 0;' +
        ' margin-right: 0; }'
      );
    });

    it('supports a null unit for "no gutter"', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-gutter: 0; }',
        'a { float: left; width: calc(99.9% * 60px); margin-left: 0;' +
        ' margin-right: 0; }'
      );
    });
  });

  describe('flexbox', function() {
    it('supports flexbox with long-form property', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-flexbox: flex; }',
        'a { flex: 0 0 auto; width: calc(99.9% * 60px - 30px);' +
        ' margin-left: 15px; margin-right: 15px; }'
      )
    });

    it('supports a custom gutter', function() {
      check(
        'a { lost-masonry-column: 60px flex; }',
        'a { flex: 0 0 auto; width: calc(99.9% * 60px - 30px);' +
        ' margin-left: 15px; margin-right: 15px; }'
      );
    });
  });

  describe('non-flexbox', function() {
    it('supports non-flexbox', function() {
      check(
        'a { lost-masonry-column: 60px no-flex; }',
        'a { float: left; width: calc(99.9% * 60px - 30px); margin-left: 15px;' +
        ' margin-right: 15px; }'
      );
    });
  });

  describe('allows for customizable rounders', function() {
    it('100%', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-rounder: 99.99999999999; }',
        'a { float: left; width: calc(99.99999999999% * 60px - 30px); margin-left: 15px;' +
        ' margin-right: 15px; }'
      );
    });

    it('99.99999999999%', function() {
      check(
        'a { lost-masonry-column: 60px; lost-masonry-column-rounder: 100; }',
        'a { float: left; width: calc(100% * 60px - 30px); margin-left: 15px;' +
        ' margin-right: 15px; }'
      );
    });
  });
});
<|endoftext|>


<commit_before>const postcss = require('postcss')
const syntax = require('postcss-less')
const path = require('path')
const fs = require('fs')
const less = require('less')
const shell = require('shelljs')

const distPath = path.resolve(__dirname, `../dist/styles/`)
shell.rm('-rf', distPath)
shell.mkdir('-p', distPath)

var pkg = require(path.join(__dirname, '../package.json'))

const p = path.resolve(__dirname, '../src/styles/')

fs.readdir(p, function (err, files) {
  if (err) {
    throw err
  }
  files.filter(function (file) {
    return !fs.statSync(path.join(p, file)).isDirectory() && /less/.test(file) && !/index|variable|theme/.test(file)
  }).forEach(function (file) {
    parse(file)
  })
})

const getPath = function (name) {
  return path.resolve(__dirname, `../dist/styles/${name}`)
}

function parse (file) {
  var code = fs.readFileSync(path.resolve(__dirname, `../src/styles/${file}`), 'utf-8')
  less.render(code, {
    compress: true,
    paths: [path.resolve(__dirname, '../src/styles')]
  },function (e, output) {
    if (e) {
      throw e
    } else {
      postcss([require('autoprefixer')(['last 2 versions'])])
      .process(output.css, {
        syntax: syntax
      })
      .then(function (result) {
        const dist = getPath(file.replace('less', 'css'));
        fs.writeFileSync(dist, result.css);
      })
      .catch(function(e){
        console.log(e)
      })
    }
  })
<<<<<<< 9a97fa54b01ee056bf9e25efd00bcf79b1225032
}
=======
}
>>>>>>> style: import reset.less instead of copying from WeUI
<commit_msg>build: Fix merge confict<commit_after>const postcss = require('postcss')
const syntax = require('postcss-less')
const path = require('path')
const fs = require('fs')
const less = require('less')
const shell = require('shelljs')

const distPath = path.resolve(__dirname, `../dist/styles/`)
shell.rm('-rf', distPath)
shell.mkdir('-p', distPath)

var pkg = require(path.join(__dirname, '../package.json'))

const p = path.resolve(__dirname, '../src/styles/')

fs.readdir(p, function (err, files) {
  if (err) {
    throw err
  }
  files.filter(function (file) {
    return !fs.statSync(path.join(p, file)).isDirectory() && /less/.test(file) && !/index|variable|theme/.test(file)
  }).forEach(function (file) {
    parse(file)
  })
})

const getPath = function (name) {
  return path.resolve(__dirname, `../dist/styles/${name}`)
}

function parse (file) {
  var code = fs.readFileSync(path.resolve(__dirname, `../src/styles/${file}`), 'utf-8')
  less.render(code, {
    compress: true,
    paths: [path.resolve(__dirname, '../src/styles')]
  },function (e, output) {
    if (e) {
      throw e
    } else {
      postcss([require('autoprefixer')(['last 2 versions'])])
      .process(output.css, {
        syntax: syntax
      })
      .then(function (result) {
        const dist = getPath(file.replace('less', 'css'));
        fs.writeFileSync(dist, result.css);
      })
      .catch(function(e){
        console.log(e)
      })
    }
  })
}
<|endoftext|>


<commit_before>var util = require('util');

var _ = require('lodash');

var validator = require('./validator.js');

function error() {
  var args = Array.prototype.slice.call(arguments, 0);
  args[0] = ' ' + args[0];
  throw new Error(util.format.apply(util, args));
}

function matchesRegex(regex) {
  return function(v) {
    if (!regex.test(v)) {
      error('Should match the regex [%s], got [%s]', regex, v);
    }
  };
}

function typeOf(match) {
  return function(e) {
    if (typeof(e) !== match) {
      error('Should be of type [%s], value was [%s]', match, e);
    }
  };
}

var isAnId = matchesRegex(/^[A-Za-z0-9\-\_]+$/);
// deviceTime is the raw, non-timezone-aware string
var isADeviceTime = matchesRegex(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
var isoPattern = /^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$/;

module.exports = function() {
  if (arguments.length > 0) {
    return validator.makeValidator.apply(validator, Array.prototype.slice.call(arguments, 0));
  }

  var optional = false;
  var fns = [];

  return _.assign(
    function(e) {
      if (optional && e == null) {
        return;
      } else if (!optional && e == null) {
        error('is required');
      }

      for (var i = 0; i < fns.length; ++i) {
        fns[i](e);
      }
    },
    {
      array: function(fn) {
        fns.push(function(e){
          if (!Array.isArray(e)) {
            error('Should be an array, value was [%s]', e);
          }

          for (var i = 0; i < e.length; ++i) {
            fn(e[i]);
          }
        });

        return this;
      },

      boolean: function() {
        fns.push(typeOf('boolean'));

        return this;
      },

      ifExists: function () {
        optional = true;
        return this;
      },

      in: function (vals) {
        var obj = {};
        for (var i = 0; i < vals.length; ++i) {
          obj[vals[i]] = true;
        }

        fns.push(function (e) {
          if (obj[e] == null) {
            error('Should be one of %j, got [%s]', vals, e);
          }
        });
        return this;
      },

      isDeviceTime: function () {
        fns.push(isADeviceTime);
        return this;
      },

      isId: function () {
        fns.push(isAnId);
        return this;
      },

      isISODateTime: function () {
        fns.push(function (value) {
          if (!isoPattern.test(value)) {
            error('Is not an ISODate string, got [%s]', value);
          }
        });
        return this;
      },

      minLength: function(length) {
        fns.push(function(e) {
          if (e.length < length) {
            error('Should have a length >= [%s], got [%s]', length, e);
          }
        });
        return this;
      },

      max: function (val) {
        fns.push(function (e) {
          if (e > val) {
            error('Should be <= [%s], got [%s]', val, e);
          }
        });
        return this;
      },

      min: function (val) {
        fns.push(function (e) {
          if (e < val) {
            error('Should be >= [%s], got [%s]', val, e);
          }
        });
        return this;
      },

      number: function () {
        fns.push(typeOf('number'));
        return this;
      },

      object: function() {
        fns.push(typeOf('object'));
        if (arguments.length > 0) {
          fns.push(module.exports(arguments[0]));
        }

        return this;
      },

      regex: function(regex) {
        fns.push(matchesRegex(regex));
        return this;
      },

      string: function() {
        fns.push(typeOf('string'));
        return this;
      }
    }
  );
};

module.exports.and = function(fields) {
  return function(e){
    var allNull = true;
    var allNotNull = true;
    for (var i = 0; i < fields.length; ++i) {
      if (e[fields[i]] == null) {
        allNotNull = false;
      } else {
        allNull = false;
      }
    }

    if (! (allNull || allNotNull)) {
      error('Fields in %j must all be present or absent, only value(s) were %j', fields, _.pick(e, fields));
    }
  };
};

module.exports.with = function(primaryField, fields) {
  if (! Array.isArray(fields)) {
    fields = [fields];
  }

  return function(e){
    if (e[primaryField] != null) {
      for (var i = 0; i < fields.length; ++i) {
        if (e[fields[i]] == null) {
          error('Field(s) %j are expected when field [%s] exists.  Value(s) were %j', fields, primaryField, _.pick(e, primaryField, fields));
        }
      }
    }
  };
};

module.exports.error = error;

<commit_msg>adjust deviceTime regex; check for undefined, not null; add oneOf<commit_after>var util = require('util');

var _ = require('lodash');

var validator = require('./validator.js');

function error() {
  var args = Array.prototype.slice.call(arguments, 0);
  args[0] = ' ' + args[0];
  throw new Error(util.format.apply(util, args));
}

function matchesRegex(regex) {
  return function(v) {
    if (!regex.test(v)) {
      error('Should match the regex [%s], got [%s]', regex, v);
    }
  };
}

function typeOf(match) {
  return function(e) {
    if (typeof(e) !== match) {
      error('Should be of type [%s], value was [%s]', match, e);
    }
  };
}

var isAnId = matchesRegex(/^[A-Za-z0-9\-\_]+$/);
// deviceTime is the raw, non-timezone-aware string
var isADeviceTime = matchesRegex(/^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d)$/);
var isoPattern = /^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$/;

module.exports = function() {
  if (arguments.length > 0) {
    return validator.makeValidator.apply(validator, Array.prototype.slice.call(arguments, 0));
  }

  var optional = false;
  var fns = [];

  return _.assign(
    function(e) {
      if (optional && e === undefined) {
        return;
      } else if (!optional && e === undefined) {
        error('is required');
      }

      for (var i = 0; i < fns.length; ++i) {
        fns[i](e);
      }
    },
    {
      array: function(fn) {
        fns.push(function(e){
          if (!Array.isArray(e)) {
            error('Should be an array, value was [%s]', e);
          }

          for (var i = 0; i < e.length; ++i) {
            fn(e[i]);
          }
        });

        return this;
      },

      boolean: function() {
        fns.push(typeOf('boolean'));

        return this;
      },

      ifExists: function () {
        optional = true;
        return this;
      },

      in: function (vals) {
        var obj = {};
        for (var i = 0; i < vals.length; ++i) {
          obj[vals[i]] = true;
        }

        fns.push(function (e) {
          if (obj[e] == null) {
            error('Should be one of %j, got [%s]', vals, e);
          }
        });
        return this;
      },

      isDeviceTime: function () {
        fns.push(isADeviceTime);
        return this;
      },

      isId: function () {
        fns.push(isAnId);
        return this;
      },

      isISODateTime: function () {
        fns.push(function (value) {
          if (!isoPattern.test(value)) {
            error('Is not an ISODate string, got [%s]', value);
          }
        });
        return this;
      },

      minLength: function(length) {
        fns.push(function(e) {
          if (e.length < length) {
            error('Should have a length >= [%s], got [%s]', length, e);
          }
        });
        return this;
      },

      max: function (val) {
        fns.push(function (e) {
          if (e > val) {
            error('Should be <= [%s], got [%s]', val, e);
          }
        });
        return this;
      },

      min: function (val) {
        fns.push(function (e) {
          if (e < val) {
            error('Should be >= [%s], got [%s]', val, e);
          }
        });
        return this;
      },

      number: function () {
        fns.push(typeOf('number'));
        return this;
      },

      object: function() {
        fns.push(typeOf('object'));
        if (arguments.length > 0) {
          fns.push(module.exports(arguments[0]));
        }

        return this;
      },

      oneOf: function() {
        var alts = [];
        for (var i = 0; i < arguments.length; ++i) {
          alts.push(module.exports(arguments[i]));
        }
        fns.push(function(e) {
          var errors = [];
          for (var i = 0; i < alts.length; ++i) {
            try {
              alts[i](e);
            }
            catch(err) {
              errors.push(err);
            }
          }
          if (errors.length > (alts.length - 1)) {
            error('Failed all schemas %j, got [%s]', _.pluck(errors, 'message'), e);
          }
        });

        return this;
      },

      regex: function(regex) {
        fns.push(matchesRegex(regex));
        return this;
      },

      string: function() {
        fns.push(typeOf('string'));
        return this;
      }
    }
  );
};

module.exports.and = function(fields) {
  return function(e){
    var allNull = true;
    var allNotNull = true;
    for (var i = 0; i < fields.length; ++i) {
      if (e[fields[i]] == null) {
        allNotNull = false;
      } else {
        allNull = false;
      }
    }

    if (! (allNull || allNotNull)) {
      error('Fields in %j must all be present or absent, only value(s) were %j', fields, _.pick(e, fields));
    }
  };
};

module.exports.with = function(primaryField, fields) {
  if (! Array.isArray(fields)) {
    fields = [fields];
  }

  return function(e){
    if (e[primaryField] != null) {
      for (var i = 0; i < fields.length; ++i) {
        if (e[fields[i]] == null) {
          error('Field(s) %j are expected when field [%s] exists.  Value(s) were %j', fields, primaryField, _.pick(e, primaryField, fields));
        }
      }
    }
  };
};

module.exports.error = error;

<|endoftext|>


<commit_before>/**
 * Created by rodriguesc on 06/03/2017.
 */

import site from './../../lib/mangafox';
import config from './_results';
import { find } from 'lodash';

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

// Then either:
const expect = chai.expect;
// or:
chai.should();
// according to your preference of assertion style

//TODO change to should assertion

describe('MangaFox live', () => {

  it('should get all mangas', done => {
    site.mangas()
      .then(mangas => {
        expect(mangas.length).to.be.gte(config.mangas_count);
        //TODO add manga verification
      })
      .then(done)
      .catch(done);

  });

  it('should get info', done => {
    let manga = 'http://mangafox.me/manga/gintama';
    site.info(manga)
      .then(x => {
        expect(x).to.exist;

        expect(x.released).to.be.eq(config.manga.released);

        expect(x.artists).to.be.deep.eq(config.manga.artists);
        expect(x.authors).to.be.deep.eq(config.manga.authors);
        expect(x.genres).to.be.deep.eq(config.manga.genres);
      })
      .should.eventually.notify(done);
  });

  it('should not find manga by name',done=>{
    let name = 'my stupid name';
    let chapter = 1;

    site.resolve(name,chapter)
      .should.eventually.be.rejectedWith(Error)
      .notify(done);
  });

  it('should not find chapter ',done=>{
    let name = 'Gintama';
    let chapter = 'oooraklhsdaosdjnalmshd';

    site.resolve(name,chapter)
      .should.eventually.be.rejectedWith(Error)
      .notify(done);
  });

  it('should get chapters', done => {
    let manga = 'http://mangafox.me/manga/gintama';

    site.chapters(manga)
      .then(x => {
        expect(x).to.exist;
        expect(x.length).to.be.eq(629);
        //TODO add chapter verification

      })
      .then(done)
      .catch(done);

  });

  it('should get images paths', done => {
    let chapter ='http://mangafox.me/manga/school_rumble/v14/c172/1.html';

    site.imagesPaths(chapter)
      .then(x => {
        expect(x).to.exist;
        expect(x.length).to.be.gte(8);
        //TODO add chapter verification
      })
      .then(done)
      .catch(done);
  });

  it('should get School : chapter 172', done => {
    let name = 'School Rumble';
    let chapter = 172;

    site.resolve(name,chapter)
      .then(images=>{
        expect(images).to.exist;
        expect(images.length).to.be.eq(8);

        images[0].then(img=>{
          expect(img).to.contain('mfcdn.net/store/manga/90/14-172.0/compressed/Townsocks_School_Rumble_172_1.jpg');
        });
      })
      .should.eventually.notify(done);
  });
});<commit_msg>change mangafox testing to be against Zui Wu Dao<commit_after>/**
 * Created by rodriguesc on 06/03/2017.
 */

import site from './../../lib/mangafox';
import config from './_results';
import { find } from 'lodash';

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

// Then either:
const expect = chai.expect;
// or:
chai.should();
// according to your preference of assertion style

//TODO change to should assertion

describe('MangaFox live', () => {

  it('should get all mangas', done => {
    site.mangas()
      .then(mangas => {
        expect(mangas.length).to.be.gte(config.mangas_count);
        //TODO add manga verification
      })
      .then(done)
      .catch(done);

  });

  it('should get info', done => {
    let manga = 'http://mangafox.me/manga/gintama';
    site.info(manga)
      .then(x => {
        expect(x).to.exist;

        expect(x.released).to.be.eq(config.manga.released);

        expect(x.artists).to.be.deep.eq(config.manga.artists);
        expect(x.authors).to.be.deep.eq(config.manga.authors);
        expect(x.genres).to.be.deep.eq(config.manga.genres);
      })
      .should.eventually.notify(done);
  });

  it('should not find manga by name',done=>{
    let name = 'my stupid name';
    let chapter = 1;

    site.resolve(name,chapter)
      .should.eventually.be.rejectedWith(Error)
      .notify(done);
  });

  it('should not find chapter ',done=>{
    let name = 'Gintama';
    let chapter = 'oooraklhsdaosdjnalmshd';

    site.resolve(name,chapter)
      .should.eventually.be.rejectedWith(Error)
      .notify(done);
  });

  it('should get chapters', done => {
    let manga = 'http://mangafox.me/manga/gintama';

    site.chapters(manga)
      .then(x => {
        expect(x).to.exist;
        expect(x.length).to.be.eq(629);
        //TODO add chapter verification

      })
      .then(done)
      .catch(done);

  });

  it('should get images paths', done => {
    let chapter ='http://mangafox.me/manga/zui_wu_dao/c042/1.html';

    site.imagesPaths(chapter)
      .then(x => {
        expect(x).to.exist;
        expect(x.length).to.be.gte(8);
        //TODO add chapter verification
      })
      .then(done)
      .catch(done);
  });

  it('should get School : chapter 172', done => {
    let name = 'Zui Wu Dao';
    let chapter = 42;

    site.resolve(name,chapter)
      .then(images=>{
        expect(images).to.exist;
        expect(images.length).to.be.eq(17);

        images[0].then(img=>{
          expect(img).to.contain('mfcdn.net/store/manga/15973/042.0/compressed/k001.jpg');
        });
      })
      .should.eventually.notify(done);
  });
});<|endoftext|>


<commit_before>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @file BusCampusDetails.js
 * @providesModule BusCampusDetails
 * @description Displays a campus' location on a map, relative to a user's location, as well as a list of the stops
 *              near the campus.
 *
 * @flow
 */
'use strict';

// React imports
import React from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';

// Type imports
import type {
  LatLong,
  LatLongDelta,
  TransitCampus,
  TransitStop,
  University,
} from 'types';

// Type definition for component props.
type Props = {
  campusColor: string,
  campusName: string,
};

// Type definition for component state.
type State = {
  campus: ?TransitCampus,
  region: ?(LatLong & LatLongDelta),
};

// Imports
const Configuration = require('Configuration');
const DisplayUtils = require('DisplayUtils');
const MapView = require('react-native-maps');
const StopDetails = require('StopDetails');

class BusCampusDetails extends React.Component {

  /**
   * Properties which the parent component should make available to this component.
   */
  static propTypes = {
    campusColor: React.PropTypes.string.isRequired,
    campusName: React.PropTypes.string.isRequired,
  };

  /**
   * Define type for the component state.
   */
  state: State;

  /**
   * Pass props and declares initial state.
   *
   * @param {Props} props properties passed from container to this component.
   */
  constructor(props: Props) {
    super(props);

    this.state = {
      campus: null,
      region: null,
    };

    // Explicitly binding 'this' to all methods that need it
    (this:any)._busStopSelected = this._busStopSelected.bind(this);
    (this:any)._getCampusMap = this._getCampusMap.bind(this);
    (this:any)._getCampusStops = this._getCampusStops.bind(this);
    (this:any)._loadCampusInfo = this._loadCampusInfo.bind(this);
  }

  /**
   * If the campus details have not been loaded, then loads them.
   */
  componentDidMount(): void {
    if (this.state.campus == null) {
      Configuration.init()
          .then(this._loadCampusInfo())
          .catch(err => console.error('Configuration could not be initialized for bus campus details.', err));
    }
  }

  /**
   * Invoked when the user selects a stop.
   *
   * @param {?TransitStop} stop properties of the selected stop.
   */
  _busStopSelected(stop: ?TransitStop): void {
    if (stop == null) {
      this.setState({
        region: null,
      });
    } else {
      // Show stop name and code
      this.refs[this._getMarkerReference(stop)].showCallout();

      // Center on the stop
      this.setState({
        region: {
          latitude: stop.lat,
          longitude: stop.long,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        },
      });
    }
  }

  /**
   * Renders a map with a list of markers to denote bus stops near the campus.
   *
   * @returns {ReactElement<any>} a {MapView} with a list of markers placed at the stops on the campus.
   */
  _getCampusMap(): ReactElement<any> {
    let markers: Array<TransitStop> = [];
    let lat: number = 0;
    let long: number = 0;
    let initialRegion: LatLong & LatLongDelta;

    if (this.state.campus == null) {
      const university: ?University = Configuration.getUniversity();
      if (university == null) {
        initialRegion = {
          latitude: 45.4222,
          longitude: -75.6824,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        };
      } else {
        lat = university.lat;
        long = university.long;
        initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        };
      }
    } else {
      lat = this.state.campus.lat;
      long = this.state.campus.long;
      initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      };

      markers = this.state.campus.stops;
    }

    // TODO: onCalloutPress (below) does not currently work for iOS
    // Follow progress at https://github.com/lelandrichardson/react-native-maps/issues/286

    return (
      <MapView
          region={this.state.region || initialRegion}
          style={_styles.map}>
        {markers.map(stop => (
          <MapView.Marker
              coordinate={{latitude: stop.lat, longitude: stop.long}}
              description={stop.code}
              key={stop.id}
              ref={this._getMarkerReference(stop)}
              title={stop.name}
              onCalloutPress={() => this._busStopSelected(stop)} />
        ))}
      </MapView>
    );
  }

  /**
   * Returns a view containing a header and list with the stops surrounding the campus provided by
   * {this.props.campusName}.
   *
   * @returns {ReactElement<any>} a {Stops} view with details about the various stops on the campus, or an empty view
   */
  _getCampusStops(): ReactElement<any> {
    if (this.state.campus == null) {
      return (
        <View style={_styles.container} />
      );
    } else {
      return (
        <StopDetails
            backgroundIsDark={DisplayUtils.isColorDark(this.props.campusColor)}
            campus={this.state.campus}
            campusName={this.props.campusName}
            onStopSelected={this._busStopSelected} />
      );
    }
  }

  /**
   * Gets a string which can be used to identify a marker on the map for a particular stop.
   *
   * @param {TransitStop} stop bus stop to get marker reference name
   * @returns {string} marker reference name
   */
  _getMarkerReference(stop: TransitStop): string {
    return (String:any).format('Marker{0}', stop.id);
  }

  /**
   * Retrieves data about the campus provided as {this.props.campusName}.
   */
  _loadCampusInfo(): void {
    Configuration.getConfig('/transit_times.json')
        .then(campuses => {
          for (let i = 0; i < campuses.length; i++) {
            if (campuses[i].id === this.props.campusName) {
              this.setState({
                campus: campuses[i],
              });
            }
          }
        })
        .catch(err => console.error('Could not get /transit_times.json.', err));
  }

  /**
   * Renders a map and list of routes and stop times at the various stops.
   *
   * @returns {ReactElement<any>} the hierarchy of views to render.
   */
  render(): ReactElement<any> {
    return (
      <View style={[_styles.container, {backgroundColor: this.props.campusColor}]}>
        <View style={_styles.mapContainer}>
          {this._getCampusMap()}
        </View>
        <View style={_styles.stopsContainer}>
          {this._getCampusStops()}
        </View>
      </View>
    );
  }
}

// Private styles for the component
const _styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  mapContainer: {
    flex: 1,
  },
  stopsContainer: {
    flex: 2,
  },
});

module.exports = BusCampusDetails;
<commit_msg>Move map to campus properly when loading bus stops<commit_after>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @file BusCampusDetails.js
 * @providesModule BusCampusDetails
 * @description Displays a campus' location on a map, relative to a user's location, as well as a list of the stops
 *              near the campus.
 *
 * @flow
 */
'use strict';

// React imports
import React from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';

// Type imports
import type {
  LatLong,
  LatLongDelta,
  TransitCampus,
  TransitStop,
  University,
} from 'types';

// Type definition for component props.
type Props = {
  campusColor: string,
  campusName: string,
};

// Type definition for component state.
type State = {
  campus: ?TransitCampus,
  initialRegion: LatLong & LatLongDelta,
  region: ?(LatLong & LatLongDelta),
};

// Imports
const Configuration = require('Configuration');
const DisplayUtils = require('DisplayUtils');
const MapView = require('react-native-maps');
const StopDetails = require('StopDetails');

class BusCampusDetails extends React.Component {

  /**
   * Properties which the parent component should make available to this component.
   */
  static propTypes = {
    campusColor: React.PropTypes.string.isRequired,
    campusName: React.PropTypes.string.isRequired,
  };

  /**
   * Define type for the component state.
   */
  state: State;

  /**
   * Pass props and declares initial state.
   *
   * @param {Props} props properties passed from container to this component.
   */
  constructor(props: Props) {
    super(props);

    this.state = {
      campus: null,
      initialRegion: {
        latitude: 45.4222,
        longitude: -75.6824,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      },
      region: null,
    };

    // Explicitly binding 'this' to all methods that need it
    (this:any)._busStopSelected = this._busStopSelected.bind(this);
    (this:any)._getCampusMap = this._getCampusMap.bind(this);
    (this:any)._getCampusStops = this._getCampusStops.bind(this);
    (this:any)._loadCampusInfo = this._loadCampusInfo.bind(this);
  }

  /**
   * If the campus details have not been loaded, then loads them.
   */
  componentDidMount(): void {
    if (this.state.campus == null) {
      Configuration.init()
          .then(this._loadCampusInfo())
          .catch(err => console.error('Configuration could not be initialized for bus campus details.', err));
    }
  }

  /**
   * Invoked when the user selects a stop.
   *
   * @param {?TransitStop} stop properties of the selected stop.
   */
  _busStopSelected(stop: ?TransitStop): void {
    if (stop == null) {
      this.setState({
        region: null,
      });
    } else {
      // Show stop name and code
      this.refs[this._getMarkerReference(stop)].showCallout();

      // Center on the stop
      this.setState({
        region: {
          latitude: stop.lat,
          longitude: stop.long,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        },
      });
    }
  }

  /**
   * Renders a map with a list of markers to denote bus stops near the campus.
   *
   * @returns {ReactElement<any>} a {MapView} with a list of markers placed at the stops on the campus.
   */
  _getCampusMap(): ReactElement<any> {
    let markers: Array<TransitStop> = [];

    if (this.state.campus != null) {
      markers = this.state.campus.stops;
    }

    // TODO: onCalloutPress (below) does not currently work for iOS
    // Follow progress at https://github.com/lelandrichardson/react-native-maps/issues/286

    return (
      <MapView
          region={this.state.region || this.state.initialRegion}
          style={_styles.map}>
        {markers.map(stop => (
          <MapView.Marker
              coordinate={{latitude: stop.lat, longitude: stop.long}}
              description={stop.code}
              key={stop.id}
              ref={this._getMarkerReference(stop)}
              title={stop.name}
              onCalloutPress={() => this._busStopSelected(stop)} />
        ))}
      </MapView>
    );
  }

  /**
   * Returns a view containing a header and list with the stops surrounding the campus provided by
   * {this.props.campusName}.
   *
   * @returns {ReactElement<any>} a {Stops} view with details about the various stops on the campus, or an empty view
   */
  _getCampusStops(): ReactElement<any> {
    if (this.state.campus == null) {
      return (
        <View style={_styles.container} />
      );
    } else {
      return (
        <StopDetails
            backgroundIsDark={DisplayUtils.isColorDark(this.props.campusColor)}
            campus={this.state.campus}
            campusName={this.props.campusName}
            onStopSelected={this._busStopSelected} />
      );
    }
  }

  /**
   * Gets a string which can be used to identify a marker on the map for a particular stop.
   *
   * @param {TransitStop} stop bus stop to get marker reference name
   * @returns {string} marker reference name
   */
  _getMarkerReference(stop: TransitStop): string {
    return (String:any).format('Marker{0}', stop.id);
  }

  /**
   * Retrieves data about the campus provided as {this.props.campusName}.
   */
  _loadCampusInfo(): void {
    Configuration.getConfig('/transit_times.json')
        .then(campuses => {
          for (let i = 0; i < campuses.length; i++) {
            if (campuses[i].id === this.props.campusName) {
              this.setState({
                campus: campuses[i],
                initialRegion: {
                  latitude: campuses[i].lat,
                  longitude: campuses[i].long,
                  latitudeDelta: 0.01,
                  longitudeDelta: 0.01,
                },
              });
            }
          }
        })
        .catch(err => console.error('Could not get /transit_times.json.', err));
  }

  /**
   * Renders a map and list of routes and stop times at the various stops.
   *
   * @returns {ReactElement<any>} the hierarchy of views to render.
   */
  render(): ReactElement<any> {
    return (
      <View style={[_styles.container, {backgroundColor: this.props.campusColor}]}>
        <View style={_styles.mapContainer}>
          {this._getCampusMap()}
        </View>
        <View style={_styles.stopsContainer}>
          {this._getCampusStops()}
        </View>
      </View>
    );
  }
}

// Private styles for the component
const _styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  mapContainer: {
    flex: 1,
  },
  stopsContainer: {
    flex: 2,
  },
});

module.exports = BusCampusDetails;
<|endoftext|>


<commit_before>general: {

    VLOOKUP : function(value, table, colIndex, approx){
        var col, row, rowLength, colLength;

        if(typeof(table == 'object') && table.constructor.name == 'Object'){
            table = utility.rangeToTable(table);
        }

        rowLength = table.length;
        colLength = table[0].length;
        colIndex  = colIndex-1;
        /** default approx to false */
        approx = typeof(approx) == 'undefined' ? false : approx;

        if(colIndex > colLength-1){
            return '#REF!';
        }

        if(colIndex < 0){
            return '#VALUE!';
        }

        if(false == approx){
            for(row = 0; row < rowLength; row++){
                if(value == table[row][0]){
                    return table[row][colIndex];
                }
            }

            return '#N/A!';
        }else{
            var delta = [], deltaMin, rowIndex, deltaLength;

            for(row = 0; row < rowLength; row++){
                if(value == table[row][0]){
                    return table[row][colIndex];
                }
                delta[row] = Math.abs(table[row][0] - value);

                if(isNaN(delta[row])){
                    delta[row] = -1;
                }

            }

            deltaLength = delta.length;
            deltaMin    = null;

            for(var a = 0; a < deltaLength; a++){
                if(delta[a] >= 0){
                    if(deltaMin === null){
                        deltaMin = delta[a];
                    }else{
                        deltaMin = (deltaMin < delta[a]) ? deltaMin : delta[a];
                    }
                }
            }

            rowIndex = delta.indexOf(deltaMin);

            if(rowIndex < 0){
                return '#N/A!';
            }

            return table[rowIndex][colIndex];
        }
    },

    HLOOKUP : function(value, table, rowIndex, approx){
        if(typeof(table == 'object')){
            table = utility.rangeToTable(table);
        }

        table = utility.transposeTable(table);

        return formula.general.VLOOKUP(value, table, rowIndex, approx);
    },

    LOOKUP : function(value, lookup, target){
        var lookupIndex, lookupLength, targetIndex, targetLength, delta = [],
            deltaLength, deltaIndex, deltaMax, deltaMin;

        target = typeof target == 'undefined' ? false : target;

        if(typeof(lookup == 'object') && lookup.constructor.name == 'Object'){
            lookup = utility.objectToArray(lookup);
            lookupLength = lookup.length;
        }

        if(typeof(target == 'object') && target.constructor.name == 'Object'){
            target = utility.objectToArray(target);
            targetLength = target.length;
        }

        if(value < Math.min.apply(Math, lookup)){
            return '#N/A!';
        }

        for(lookupIndex = 0; lookupIndex < lookupLength; lookupIndex++){

            if(value == lookup[lookupIndex]){
                return target ? target[lookupIndex] : lookup[lookupIndex];
            }else{
                delta[lookupIndex] = value - lookup[lookupIndex];
            }
        }

        /** convert minus to max */
        deltaLength = delta.length;
        deltaMax    = Math.max.apply(Math, delta);
        for(deltaIndex = 0; deltaIndex < deltaLength; deltaIndex++){
            if(delta[deltaIndex] < 0){
                delta[deltaIndex] = deltaMax;
            }
        }

        deltaMin = Math.min.apply(Math, delta);
        lookupIndex = delta.indexOf(deltaMin);

        return (target) ? target[lookupIndex] : lookup[lookupIndex];

    },

    SERVER : function(){
        if(this.config.ajaxUrl == null){
            return data.ERRKEY.ajaxUrlRequired;
        }

        var result,
            funcName = arguments[0],
            params = {};

        for (var a = 1; a < arguments.length; a++){
            params['params['+a+']'] = arguments[a];
        }

        params['function'] = funcName;

        $.ajax({
            url: this.config.ajaxUrl,
            method: this.config.ajaxMethod,
            data: params,
            async: false,
            success: function(response){
                result = response;
            },
            error: function(response){
                result = data.ERRKEY.sendRequestError;
            }
        });

        return result;
    },

    GRAPH : function(data, options){

        var graphOptions= {},
            cellElement = this.getActiveCell().el,
            plotOptions = {},
            options     = (typeof(options) == 'undefined') ? [] : options,
            keyval, graphData;

        /**
         * parsing option come from formula into javascript object
         */
        for(var a = 0; a < options.length; a++){
            keyval = options[a].split('=');
            graphOptions[keyval[0]] = keyval[1];
        }

        /**
         * setup default height and width
         */
        if(!cellElement.height()){
            cellElement.css('height', '300px');
        }

        if(!cellElement.width){
            cellElement.css('width', '300px');
        }

        switch(graphOptions.type){
            case 'bar':
                graphData   = utility.rangeToTable(data);
                if(typeof(graphOptions.reverse != 'undefined') && graphOptions.reverse == 'true'){
                    graphData.reverse();
                }
                plotOptions.series = {
                    bars: {
                        show: true,
                        barWidth: 0.6,
                        align: "center"
                    },
                    stack: true
                };
                if(typeof(graphOptions.bar_orientation) != 'undefined' && graphOptions.bar_orientation == 'horizontal'){
                    plotOptions.series.bars.horizontal = true;
                }
                break;

            case 'pie':
                graphData   = utility.objectToArray(data);
                plotOptions.series = {
                    pie: {
                        show: true,
                        radius: 0.8
                    }
                };
                plotOptions.legend = {
                    show:false
                }
                break;

            case 'doughnut':
            case 'donut':
                graphData   = utility.objectToArray(data);
                plotOptions.series = {
                    pie: {
                        show: true,
                        innerRadius: 0.5,
                        radius: 0.8
                    }
                };
                plotOptions.legend = {
                    show:false
                }
                break;

            default:
                graphData   = utility.rangeToTable(data);
                if(typeof(graphOptions.reverse != 'undefined') && graphOptions.reverse == 'true'){
                    graphData.reverse();
                }
                break;
        }

        /**
         * change the table orientation if configured
         */
        if(typeof(graphOptions.orientation) != 'undefined' && graphOptions.orientation == 'vertical'){
            graphData = utility.transposeTable(graphData);
        }

        /**
         * parsing label as x-axis label
         */
        if(typeof(graphOptions.label) != 'undefined'){
            var label = this.evaluate(graphOptions.label),
                label = utility.objectToArray(label),
                rowLength = graphData.length,
                colLength, row, col, data;

            for(row = 0; row < rowLength; row++){

                colLength = graphData[row].length;

                for(col = 0; col < colLength; col++){
                    data = graphData[row][col];
                    graphData[row][col] = [label[col], data];
                }
            }

            plotOptions.xaxis = {
                mode: "categories",
                tickLength: 0
            };
        }else{

            var rowLength = graphData.length,
                colLength, row, col, data;

            for(row = 0; row < rowLength; row++){

                colLength = graphData[row].length;

                for(col = 0; col < colLength; col++){
                    data = graphData[row][col];
                    if(typeof(graphOptions.bar_orientation) != 'undefined' && graphOptions.bar_orientation == 'horizontal'){
                        graphData[row][col] = [data, col];
                    }else{
                        graphData[row][col] = [col, data];
                    }
                }
            }
        }

        /**
         * parsing legend and merge with the graph data
         */
        if(typeof(graphOptions.legend) != 'undefined'){
            var legend = this.evaluate(graphOptions.legend),
                legend = utility.objectToArray(legend),
                newGraphData = [];

            for(var graphLength = 0; graphLength < graphData.length; graphLength++){
                newGraphData.push({
                    label : legend[graphLength],
                    data  : graphData[graphLength]
                });
            }

            graphData = newGraphData;
        }

        /**
         * hide and show axis label
         */
        if(typeof(graphOptions.show_x_axis) != 'undefined' && graphOptions.show_x_axis == 'false'){
            plotOptions.xaxis = plotOptions.xaxis || {};
            plotOptions.xaxis.show = false;
        }

        if(typeof(graphOptions.show_y_axis) != 'undefined' && graphOptions.show_y_axis == 'false'){
            plotOptions.yaxis = plotOptions.yaxis || {};
            plotOptions.yaxis.show = false;
        }

        plotOptions.grid = {
            backgroundColor: { colors: [ "#fff", "#eee" ] },
            borderWidth: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 0
            }
        };

        setTimeout(function(){
            $.plot(cellElement, graphData, plotOptions);
        }, 100);

        return false;

    }
}<commit_msg>fix vlookup behaviour<commit_after>general: {

    VLOOKUP: function(value, table, colIndex, approx) {
        var col, row, rowLength, colLength;

        if (typeof(table == 'object') && table.constructor.name == 'Object') {
            table = utility.rangeToTable(table);
        }

        rowLength = table.length;
        colLength = table[0].length;
        colIndex  = colIndex - 1;
        /** default approx to false */
        approx = typeof(approx) == 'undefined' ? false : approx;

        if (colIndex > colLength - 1) {
            return '#REF!';
        }

        if (colIndex < 0) {
            return '#VALUE!';
        }

        if (false == approx) {
            for (row = 0; row < rowLength; row++) {
                if (value == table[row][0]) {
                    return table[row][colIndex];
                }
            }

            return '#N/A!';
        } else {
            var delta = {}, deltaMax, deltaLength, difference;

            /** collect the difference between value on index 0, dismiss if delta is positive */
            for (row = 0; row < rowLength; row++) {
                if (value == table[row][0]) {
                    return table[row][colIndex];
                }

                difference = table[row][0] - value;

                if (difference < 0) {
                    delta[row] = difference;
                }
            }

            var deltaLength = delta.length;
            var deltaMax = null;
            var rowIndex = null;

            for (var a in delta) {
                if (deltaMax == null) {
                    deltaMax = delta[a];
                    rowIndex = a;
                } else {
                    deltaMax = (deltaMax > delta[a]) ? deltaMax : delta[a];
                    rowIndex = (deltaMax > delta[a]) ? rowIndex : a;
                }
            }

            if (rowIndex == null) {
                return '#N/A!';
            }

            return table[rowIndex][colIndex];
        }
    },

    HLOOKUP: function(value, table, rowIndex, approx) {
        if (typeof(table == 'object')) {
            table = utility.rangeToTable(table);
        }

        table = utility.transposeTable(table);

        return formula.general.VLOOKUP(value, table, rowIndex, approx);
    },

    LOOKUP: function(value, lookup, target) {
        var lookupIndex, lookupLength, targetIndex, targetLength, delta = [],
            deltaLength, deltaIndex, deltaMax, deltaMin;

        target = typeof target == 'undefined' ? false : target;

        if (typeof(lookup == 'object') && lookup.constructor.name == 'Object') {
            lookup = utility.objectToArray(lookup);
            lookupLength = lookup.length;
        }

        if (typeof(target == 'object') && target.constructor.name == 'Object') {
            target = utility.objectToArray(target);
            targetLength = target.length;
        }

        if (value < Math.min.apply(Math, lookup)) {
            return '#N/A!';
        }

        for (lookupIndex = 0; lookupIndex < lookupLength; lookupIndex++) {

            if (value == lookup[lookupIndex]) {
                return target ? target[lookupIndex] : lookup[lookupIndex];
            } else {
                delta[lookupIndex] = value - lookup[lookupIndex];
            }
        }

        /** convert minus to max */
        deltaLength = delta.length;
        deltaMax = Math.max.apply(Math, delta);
        for (deltaIndex = 0; deltaIndex < deltaLength; deltaIndex++) {
            if (delta[deltaIndex] < 0) {
                delta[deltaIndex] = deltaMax;
            }
        }

        deltaMin = Math.min.apply(Math, delta);
        lookupIndex = delta.indexOf(deltaMin);

        return (target) ? target[lookupIndex] : lookup[lookupIndex];

    },

    SERVER: function() {
        if (this.config.ajaxUrl == null) {
            return data.ERRKEY.ajaxUrlRequired;
        }

        var result,
            funcName = arguments[0],
            params = {};

        for (var a = 1; a < arguments.length; a++) {
            params['params[' + a + ']'] = arguments[a];
        }

        params['function'] = funcName;

        $.ajax({
            url: this.config.ajaxUrl,
            method: this.config.ajaxMethod,
            data: params,
            async: false,
            success: function(response) {
                result = response;
            },
            error: function(response) {
                result = data.ERRKEY.sendRequestError;
            }
        });

        return result;
    },

    GRAPH: function(data, options) {

        var graphOptions = {},
            cellElement = this.getActiveCell().el,
            plotOptions = {},
            options = (typeof(options) == 'undefined') ? [] : options,
            keyval, graphData;

        /**
         * parsing option come from formula into javascript object
         */
        for (var a = 0; a < options.length; a++) {
            keyval = options[a].split('=');
            graphOptions[keyval[0]] = keyval[1];
        }

        /**
         * setup default height and width
         */
        if (!cellElement.height()) {
            cellElement.css('height', '300px');
        }

        if (!cellElement.width) {
            cellElement.css('width', '300px');
        }

        switch (graphOptions.type) {
            case 'bar':
                graphData = utility.rangeToTable(data);
                if (typeof(graphOptions.reverse != 'undefined') && graphOptions.reverse == 'true') {
                    graphData.reverse();
                }
                plotOptions.series = {
                    bars: {
                        show: true,
                        barWidth: 0.6,
                        align: "center"
                    },
                    stack: true
                };
                if (typeof(graphOptions.bar_orientation) != 'undefined' && graphOptions.bar_orientation == 'horizontal') {
                    plotOptions.series.bars.horizontal = true;
                }
                break;

            case 'pie':
                graphData = utility.objectToArray(data);
                plotOptions.series = {
                    pie: {
                        show: true,
                        radius: 0.8
                    }
                };
                plotOptions.legend = {
                    show: false
                }
                break;

            case 'doughnut':
            case 'donut':
                graphData = utility.objectToArray(data);
                plotOptions.series = {
                    pie: {
                        show: true,
                        innerRadius: 0.5,
                        radius: 0.8
                    }
                };
                plotOptions.legend = {
                    show: false
                }
                break;

            default:
                graphData = utility.rangeToTable(data);
                if (typeof(graphOptions.reverse != 'undefined') && graphOptions.reverse == 'true') {
                    graphData.reverse();
                }
                break;
        }

        /**
         * change the table orientation if configured
         */
        if (typeof(graphOptions.orientation) != 'undefined' && graphOptions.orientation == 'vertical') {
            graphData = utility.transposeTable(graphData);
        }

        /**
         * parsing label as x-axis label
         */
        if (typeof(graphOptions.label) != 'undefined') {
            var label = this.evaluate(graphOptions.label),
                label = utility.objectToArray(label),
                rowLength = graphData.length,
                colLength, row, col, data;

            for (row = 0; row < rowLength; row++) {

                colLength = graphData[row].length;

                for (col = 0; col < colLength; col++) {
                    data = graphData[row][col];
                    graphData[row][col] = [label[col], data];
                }
            }

            plotOptions.xaxis = {
                mode: "categories",
                tickLength: 0
            };
        } else {

            var rowLength = graphData.length,
                colLength, row, col, data;

            for (row = 0; row < rowLength; row++) {

                colLength = graphData[row].length;

                for (col = 0; col < colLength; col++) {
                    data = graphData[row][col];
                    if (typeof(graphOptions.bar_orientation) != 'undefined' && graphOptions.bar_orientation == 'horizontal') {
                        graphData[row][col] = [data, col];
                    } else {
                        graphData[row][col] = [col, data];
                    }
                }
            }
        }

        /**
         * parsing legend and merge with the graph data
         */
        if (typeof(graphOptions.legend) != 'undefined') {
            var legend = this.evaluate(graphOptions.legend),
                legend = utility.objectToArray(legend),
                newGraphData = [];

            for (var graphLength = 0; graphLength < graphData.length; graphLength++) {
                newGraphData.push({
                    label: legend[graphLength],
                    data: graphData[graphLength]
                });
            }

            graphData = newGraphData;
        }

        /**
         * hide and show axis label
         */
        if (typeof(graphOptions.show_x_axis) != 'undefined' && graphOptions.show_x_axis == 'false') {
            plotOptions.xaxis = plotOptions.xaxis || {};
            plotOptions.xaxis.show = false;
        }

        if (typeof(graphOptions.show_y_axis) != 'undefined' && graphOptions.show_y_axis == 'false') {
            plotOptions.yaxis = plotOptions.yaxis || {};
            plotOptions.yaxis.show = false;
        }

        plotOptions.grid = {
            backgroundColor: {
                colors: ["#fff", "#eee"]
            },
            borderWidth: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 0
            }
        };

        setTimeout(function() {
            $.plot(cellElement, graphData, plotOptions);
        }, 100);

        return false;

    }
}<|endoftext|>


<commit_before>'use strict';
// Require the needed npm modules.
const gulp = require('gulp'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	maps = require('gulp-sourcemaps'),
	useref = require('gulp-useref'),
	iff = require('gulp-if'),
	csso = require('gulp-csso'),
	concat = require('gulp-concat'),
	imagemin = require('gulp-imagemin'),
	del = require('del'),
	browserSync = require('browser-sync'),
	pump = require('pump'),  // pump is a wrapper for .pipe that gives moar readable error messages.
	QPromise = require('q');  //	https://www.npmjs.com/package/q
// Variables w/ path to source & dist folders.
const options = {
	src: 'src',
	dist: 'dist'
};

/* Gulp Tasks      *********************************************************/
// Runs jsMinify task first, then creates source map, concats the two JS files.
gulp.task('scripts', (callback) => {
	pump([
		gulp.src([options.src + '/js/circle/*.js']),
		maps.init(),
		concat('all.min.js'),
		uglify(),
		maps.write('./'),
		gulp.dest(options.dist + '/scripts/')
	],
	callback
	);
});

/*gulp.task('jsMinify', (callback) => {
	//	Minifies the one JS file that needs it, since js/autogrow.js is already minified.
	pump([
		gulp.src(options.src + '/js/circle/*.js'),
		rename('global.js'),
		gulp.dest(options.src + '/js/')
	],
	callback
	);
});*/

gulp.task('cssMinify', (callback) => {
	pump([
		gulp.src(options.src + '/sass/global.scss'),
		maps.init({ largeFile: true }),
		sass(),
		maps.write('./'),
		gulp.dest(options.dist + '/styles/'),
		gulp.dest(options.src + '/css/'),
	],
	callback
	);
});
// Needed in order to meet rubric for styles task to compile, concat & minify all SaSS files.
gulp.task('styles', ['cssMinify'], (callback) => {
	pump([
		gulp.src(options.dist + '/styles/global.css'),
		csso(),
		rename('all.min.css'),
		gulp.dest(options.dist + '/styles/'),
		gulp.dest(options.src + '/css/'),
		browserSync.reload({
			stream: true
		})
	],
	callback
	);
});

gulp.task('images', (callback) => {
	// Uses gulp-imagemin module to optimize the images for production.
	pump([
		gulp.src(options.src + '/images/*'),
		imagemin(),
		gulp.dest(options.dist + '/content')
	],
	callback
	);
});
gulp.task('clean', ()=> {
	// Deletes all of the files and folders in the dist folder & other files created from tasks.
	return del(['dist/*', 'src/css/']);
});
// Takes the index.html file & runs it thru useref().  Runs the clean, scripts, styles & images tasks as dependencies.  Then any JS scripts & CSS links in the index.html get concated, minified for production.
gulp.task('html', ['scripts', 'styles', 'images'], (callback)=> {
	pump([
		gulp.src(options.src + '/index.html'),

		// TODO: fix this bug.?  Is it even in this task tho?

		useref(),		// useref() here fixs bug of all.min.js, all.min.css ARE minified. BUT the Source Maps Are Still NOT Working!  Clearly, this is where the useref() belongs.

		iff('*.js', uglify()),

		iff('*.css', csso()),
		// .pipe(useref())	// useref() here creates bug of all.min.css NOT minified.
		gulp.dest(options.dist)
	],
	callback
	);
});
//  Runs the clean, scripts, styles, and images tasks. Setups the project development files into a folder for production.
gulp.task('build', ['clean'], (callback) => {
	pump([
		gulp.start('html'),
		// Provide static production files below:
		gulp.src(['src/icons/**/*',
							'src/index.html'],
							{ base: './src/' }),
		gulp.dest('dist')
	],
	callback
	);
});

gulp.task('default', ['build'], (callback) => {
	// When the default gulp command is run, it continuously watches for changes to any .scss file in the project.  Runs the build task as a dependency, then serves the project using a local webserver.
	pump([
		gulp.start('watchFiles'),
		browserSync.init({
			server: {
				baseDir: 'dist'
			}
		})
	],
	callback
	);
});

// This task runs 'styles' as dependency, & then itself is run as a dependency of the 'watch' task.  Then it will minify the global.css file w/ csso(), update the production directory file & update the browser, displaying the changes.
gulp.task('watchFiles', ['styles'], (callback) => {
	pump([
		gulp.watch(options.src + '/sass/**/*.scss', ['styles']),
		gulp.src(options.src + '/index.html'),

			// TODO: Fix bug here too. Same problem as above, source maps NOT working, Ggrrrrr!

		useref(),
		iff('*.js', uglify()),
		iff('*.css', csso()),
		//.pipe(useref())When 'watchFiles' runs, then all.min.css does NOT get minified & is overwritten w/ a copy of global.css.
		gulp.dest(options.dist)
		/*.pipe(browserSync.reload({
			stream: true
		}));*/
	],
	callback
	);
});
<commit_msg>Scripts task works.<commit_after>'use strict';
// Require the needed npm modules.
const gulp = require('gulp'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	maps = require('gulp-sourcemaps'),
	useref = require('gulp-useref'),
	iff = require('gulp-if'),
	csso = require('gulp-csso'),
	concat = require('gulp-concat'),
	imagemin = require('gulp-imagemin'),
	del = require('del'),
	browserSync = require('browser-sync'),
	pump = require('pump'),  // pump is a wrapper for .pipe that gives moar readable error messages.
	QPromise = require('q');  //	https://www.npmjs.com/package/q
// Variables w/ path to source & dist folders.
const options = {
	src: 'src',
	dist: 'dist'
};

/* Gulp Tasks      *********************************************************/
// TODO: THIS BRANCH IS FOR CHECKING ALL THE TASKS ARE WORKING.
gulp.task('scripts', (callback) => {
	pump([
		gulp.src([options.src + '/js/circle/*.js']),
		maps.init(),
		concat('all.min.js'),
		uglify(),
		maps.write('./'),
		gulp.dest(options.src + '/scripts/'),
		// rename('all.min.js'),
		gulp.dest(options.src + '/scripts/')
	],
	callback
	);
});
gulp.task('cssMinify', (callback) => {
	pump([
		gulp.src(options.src + '/sass/global.scss'),
		maps.init({ largeFile: true }),
		sass(),
		maps.write('./'),
		gulp.dest(options.dist + '/styles/'),
		gulp.dest(options.src + '/css/'),
	],
	callback
	);
});
// Needed in order to meet rubric for styles task to compile, concat & minify all SaSS files.
gulp.task('styles', ['cssMinify'], (callback) => {
	pump([
		gulp.src(options.dist + '/styles/global.css'),
		csso(),
		rename('all.min.css'),
		gulp.dest(options.dist + '/styles/'),
		gulp.dest(options.src + '/css/'),
		browserSync.reload({
			stream: true
		})
	],
	callback
	);
});

gulp.task('images', (callback) => {
	// Uses gulp-imagemin module to optimize the images for production.
	pump([
		gulp.src(options.src + '/images/*'),
		imagemin(),
		gulp.dest(options.dist + '/content')
	],
	callback
	);
});
gulp.task('clean', ()=> {
	// Deletes all of the files and folders in the dist folder & other files created from tasks.
	return del(['dist/*', 'src/css/']);
});
// Takes the index.html file & runs it thru useref().  Runs the clean, scripts, styles & images tasks as dependencies.  Then any JS scripts & CSS links in the index.html get concated, minified for production.
gulp.task('html', ['scripts', 'styles', 'images'], (callback)=> {
	pump([
		gulp.src(options.src + '/index.html'),

		// TODO: fix this bug.?  Is it even in this task tho?

		useref(),		// useref() here fixs bug of all.min.js, all.min.css ARE minified. BUT the Source Maps Are Still NOT Working!  Clearly, this is where the useref() belongs.

		iff('*.js', uglify()),

		iff('*.css', csso()),
		// .pipe(useref())	// useref() here creates bug of all.min.css NOT minified.
		gulp.dest(options.dist)
	],
	callback
	);
});
//  Runs the clean, scripts, styles, and images tasks. Setups the project development files into a folder for production.
gulp.task('build', ['clean'], (callback) => {
	pump([
		gulp.start('html'),
		// Provide static production files below:
		gulp.src(['src/icons/**/*',
							'src/index.html'],
							{ base: './src/' }),
		gulp.dest('dist')
	],
	callback
	);
});

gulp.task('default', ['build'], (callback) => {
	// When the default gulp command is run, it continuously watches for changes to any .scss file in the project.  Runs the build task as a dependency, then serves the project using a local webserver.
	pump([
		gulp.start('watchFiles'),
		browserSync.init({
			server: {
				baseDir: 'dist'
			}
		})
	],
	callback
	);
});

// This task runs 'styles' as dependency, & then itself is run as a dependency of the 'watch' task.  Then it will minify the global.css file w/ csso(), update the production directory file & update the browser, displaying the changes.
gulp.task('watchFiles', ['styles'], (callback) => {
	pump([
		gulp.watch(options.src + '/sass/**/*.scss', ['styles']),
		gulp.src(options.src + '/index.html'),

			// TODO: Fix bug here too. Same problem as above, source maps NOT working, Ggrrrrr!

		useref(),
		iff('*.js', uglify()),
		iff('*.css', csso()),
		//.pipe(useref())When 'watchFiles' runs, then all.min.css does NOT get minified & is overwritten w/ a copy of global.css.
		gulp.dest(options.dist)
		/*.pipe(browserSync.reload({
			stream: true
		}));*/
	],
	callback
	);
});
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const es = require('event-stream');
const _ = require('underscore');
const util = require('gulp-util');

const allErrors = [];
let startTime = null;
let count = 0;

function onStart() {
	if (count++ > 0) {
		return;
	}

	startTime = new Date().getTime();
	util.log(util.colors.green('Starting compilation'));
}

function onEnd() {
	if (--count > 0) {
		return ;
	}

	var errors = _.flatten(allErrors);
	errors.map(err => util.log(`${ util.colors.red('Error') }: ${ err }`));

	util.log(`${ util.colors.green('Finished compilation') } with ${ util.colors.red(errors.length + ' errors') } in ${ util.colors.blue((new Date().getTime() - startTime) + 'ms') }.`);
}

module.exports = function () {
	var errors = [];
	allErrors.push(errors);

	var result = function (err) {
		errors.push(err);
	};

	result.end = function (emitError) {
		errors.length = 0;
		onStart();
		return es.through(null, function () {
			onEnd();

			if (emitError && errors.length > 0) {
				this.emit('error', 'Errors occurred.');
			} else {
				this.emit('end');
			}
		});
	};

	result.hasErrors = function() {
		return errors.length > 0;
	}

	return result;
};<commit_msg>fixes #9269<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const es = require('event-stream');
const _ = require('underscore');
const util = require('gulp-util');

const allErrors = [];
let startTime = null;
let count = 0;

function onStart() {
	if (count++ > 0) {
		return;
	}

	startTime = new Date().getTime();
	util.log(`Starting ${ util.colors.green('compilation') }...`);
}

function onEnd() {
	if (--count > 0) {
		return ;
	}

	var errors = _.flatten(allErrors);
	errors.map(err => util.log(`${ util.colors.red('Error') }: ${ err }`));

	util.log(`Finished ${ util.colors.green('compilation') } with ${ errors.length } errors after ${ util.colors.magenta((new Date().getTime() - startTime) + ' ms') }`);
}

module.exports = function () {
	var errors = [];
	allErrors.push(errors);

	var result = function (err) {
		errors.push(err);
	};

	result.end = function (emitError) {
		errors.length = 0;
		onStart();
		return es.through(null, function () {
			onEnd();

			if (emitError && errors.length > 0) {
				this.emit('error', 'Errors occurred.');
			} else {
				this.emit('end');
			}
		});
	};

	result.hasErrors = function() {
		return errors.length > 0;
	}

	return result;
};<|endoftext|>