<commit_before>
// depth = 2 minimax

const calculatePieceValue = (pieceType, color) => {
  let score;
  switch (pieceType) {
    case 'p':
      score = 100;
      break;
    case 'n':
      score = 320;
      break;
    case 'b':
      score = 325;
      break;
    case 'r':
      score = 500;
      break;
    case 'q':
      score = 975;
      break;
    case 'k':
      score = 32767;
      break;
    default:
      return;
  }
  if (color === 'b') {
    score = -score;
  }
  return score;
};

const calculatePositionValue = (pieceType, color, i, j, numRounds) => {
  let chessTable;
  switch (pieceType) {
    case 'p':
      chessTable = [[  0,  0,  0,  0,  0,  0,  0,  0],
                    [ 50, 50, 50, 50, 50 ,50 ,50, 50],
                    [ 10, 10, 20, 30, 30, 20, 10, 10],
                    [  5,  5, 10, 27, 27, 10,  5,  5],
                    [  0,  0,  0, 25, 25,  0,  0,  0],
                    [  5, -5,-10,  0,  0,-10, -5,  5],
                    [  5, 10, 10,-25,-25, 10, 10,  5],
                    [  0,  0,  0,  0,  0,  0,  0,  0]];
      break;
    case 'n':
      chessTable = [[-50,-40,-30,-30,-30,-30,-40,-50],
                    [-40,-20,  0,  0,  0,  0,-20,-40],
                    [-30,  0, 10, 15, 15, 10,  0,-30],
                    [-30,  5, 15, 20, 20, 15,  5,-30],
                    [-30,  0, 15, 20, 20, 15,  0,-30],
                    [-30,  5, 10, 15, 15, 10,  5,-30],
                    [-40,-20,  0,  5,  5,  0,-20,-40],
                    [-50,-40,-20,-30,-30,-20,-40,-50]];
      break;
    case 'b':
      chessTable = [[-20,-10,-10,-10,-10,-10,-10,-20],
                    [-10,  0,  0,  0,  0,  0,  0,-10],
                    [-10,  0,  5, 10, 10,  5,  0,-10],
                    [-10,  5,  5, 10, 10,  5,  5,-10],
                    [-10,  0, 10, 10, 10, 10,  0,-10],
                    [-10, 10, 10, 10, 10, 10, 10,-10],
                    [-10,  5,  0,  0,  0,  0,  5,-10],
                    [-20,-10,-40,-10,-10,-40,-10,-20]];
      break;
    case 'k':
      chessTable = [[-30,-40,-40,-50,-50,-40,-40,-30],
                    [-30,-40,-40,-50,-50,-40,-40,-30],
                    [-30,-40,-40,-50,-50,-40,-40,-30],
                    [-30,-40,-40,-50,-50,-40,-40,-30],
                    [-20,-30,-30,-40,-40,-30,-30,-20],
                    [-10,-20,-20,-20,-20,-20,-20,-10],
                    [ 20, 20,  0,  0,  0,  0, 20, 20],
                    [ 20, 30, 10,  0,  0, 10, 30, 20]];
      break;
    default:
      return;
  }
  // late game strategy for king
  if (pieceType === 'k' && numRounds > 20) {
    chessTable = [[-50,-40,-30,-20,-20,-30,-40,-50],
                  [-30,-20,-10,  0,  0,-10,-20,-30],
                  [-30,-10, 20, 30, 30, 20,-10,-30],
                  [-30,-10, 30, 40, 40, 30,-10,-30],
                  [-30,-10, 30, 40, 40, 30,-10,-30],
                  [-30,-10, 20, 30, 30, 20,-10,-30],
                  [-30,-30,  0,  0,  0,  0,-30,-30],
                  [-50,-30,-30,-30,-30,-30,-30,-50]];
  }
  let positionValue = chessTable[i][j];
  if (color === 'b') {
    positionValue = -1 * chessTable[7 - i][7 - j];
  }
  return positionValue;
};

// AI looks for move with lowest total board value
const sumBoardValue = (board, numRounds) => {
  let value = 0;
  for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 8; j++) {
      if (board[i][j]) {
        value += calculatePieceValue(board[i][j].type, board[i][j].color);
        if (['r', 'q'].indexOf(board[i][j].type) === -1) {
          // no special late game strategy for now
          value += calculatePositionValue(board[i][j].type, board[i][j].color, i, j, 10);
        }
      }
    }
  }
  return value;
};

const indexOfMin = (arr) => {
  if (arr.length === 0) {
    return -1;
  }
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
      minIndex = i;
      min = arr[i];
    }
  }
  return minIndex;
};

// sort tuple values from small to large
const sortBySecondElement = (a, b) => {
  if (a[1] === b[1]) {
    return 0;
  }
  return (a[1] < b[1]) ? -1 : 1;
};

const YellowSubsAction = (game, depth) => {
  let valueAfterOnePly = [];
  let possibleMovesBlack = game.moves();

  for (let k = 0; k < possibleMovesBlack.length; k++) {
    game.move(possibleMovesBlack[k]);
    const valueAfterBlackMove = sumBoardValue(game.board());
    valueAfterOnePly.push([possibleMovesBlack[k], valueAfterBlackMove]);
    game.undo();
  }

  valueAfterOnePly.sort(sortBySecondElement);

  let lowestValue = Infinity;
  const whiteMoveValuesOnly = [];
  const whiteMoveAndValue = [];

  for (let s = 0; s < valueAfterOnePly.length; s++) {
    if (valueAfterOnePly[s][1] > lowestValue) {
      break;
    }

    game.move(valueAfterOnePly[s][0]);
    let highestValue = -Infinity;
    // let moveandvalue=[];
    const possibleMovesWhite = game.moves();

    for (let t = 0; t < possibleMovesWhite.length; t++) {
      game.move(possibleMovesWhite[t]);
      const valueAfterWhiteMove = sumBoardValue(game.board());
      if (valueAfterWhiteMove > highestValue) {
        highestValue = valueAfterWhiteMove;
        // moveAndValue = [possibleMovesWhite[t], highestValue];
      }
      game.undo();
    }

    // record best white move value for each black move
    if (highestValue < lowestValue) {
      lowestValue = highestValue;
    }

    whiteMoveValuesOnly.push(highestValue);
    // whiteMoveAndValue.push(moveAndValue);
    game.undo();
  }

  // console.log("best white move for each black move", whiteMoveAndValue);
  const bestBlackMoveIndex = indexOfMin(whiteMoveValuesOnly);
  const bestMove = valueAfterOnePly[bestBlackMoveIndex][0];
  return bestMove;
};

export { YellowSubsAction };
<commit_msg>adding rook and q fields<commit_after>
// depth = 2 minimax

const calculatePieceValue = (pieceType, color) => {
  let score;
  switch (pieceType) {
    case 'p':
      score = 100;
      break;
    case 'n':
      score = 320;
      break;
    case 'b':
      score = 325;
      break;
    case 'r':
      score = 500;
      break;
    case 'q':
      score = 975;
      break;
    case 'k':
      score = 32767;
      break;
    default:
      return;
  }
  if (color === 'b') {
    score = -score;
  }
  return score;
};

const calculatePositionValue = (pieceType, color, i, j, numRounds) => {
  let chessTable;
  switch (pieceType) {
    case 'p':
      chessTable = [[  0,  0,  0,  0,  0,  0,  0,  0],
                    [ 50, 50, 50, 50, 50 ,50 ,50, 50],
                    [ 10, 10, 20, 30, 30, 20, 10, 10],
                    [  5,  5, 10, 27, 27, 10,  5,  5],
                    [  0,  0,  0, 25, 25,  0,  0,  0],
                    [  5, -5,-10,  0,  0,-10, -5,  5],
                    [  5, 10, 10,-25,-25, 10, 10,  5],
                    [  0,  0,  0,  0,  0,  0,  0,  0]];
      break;
    case 'n':
      chessTable = [[-50,-40,-30,-30,-30,-30,-40,-50],
                    [-40,-20,  0,  0,  0,  0,-20,-40],
                    [-30,  0, 10, 15, 15, 10,  0,-30],
                    [-30,  5, 15, 20, 20, 15,  5,-30],
                    [-30,  0, 15, 20, 20, 15,  0,-30],
                    [-30,  5, 10, 15, 15, 10,  5,-30],
                    [-40,-20,  0,  5,  5,  0,-20,-40],
                    [-50,-40,-20,-30,-30,-20,-40,-50]];
      break;
    case 'b':
      chessTable = [[-20,-10,-10,-10,-10,-10,-10,-20],
                    [-10,  0,  0,  0,  0,  0,  0,-10],
                    [-10,  0,  5, 10, 10,  5,  0,-10],
                    [-10,  5,  5, 10, 10,  5,  5,-10],
                    [-10,  0, 10, 10, 10, 10,  0,-10],
                    [-10, 10, 10, 10, 10, 10, 10,-10],
                    [-10,  5,  0,  0,  0,  0,  5,-10],
                    [-20,-10,-40,-10,-10,-40,-10,-20]];
      break;
    case 'k':
      chessTable = [[-30,-40,-40,-50,-50,-40,-40,-30],
                    [-30,-40,-40,-50,-50,-40,-40,-30],
                    [-30,-40,-40,-50,-50,-40,-40,-30],
                    [-30,-40,-40,-50,-50,-40,-40,-30],
                    [-20,-30,-30,-40,-40,-30,-30,-20],
                    [-10,-20,-20,-20,-20,-20,-20,-10],
                    [ 20, 20,  0,  0,  0,  0, 20, 20],
                    [ 20, 30, 10,  0,  0, 10, 30, 20]];
      break;
    case 'q':
      chessTable = [[-20,-10,-10,-50,-50,-10,-10,-20],
                    [-10,  0,  0,  0,  0,  0,  0,-10],
                    [-10,  0,  5,  5,  5,  5,  0, 10],
                    [ -5,  0,  5,  5,  5,  5,  0, -5],
                    [  0,  0,  5,  5,  5,  5,  0, -5],
                    [-10,  5,  5,  5,  5,  5,  0,-10],
                    [-10,  0,  5,  0,  0,  0,  0,-10],
                    [-20,-10,-10,-50,-50,-10,-10,-20]];
      break;
    case 'r':
      chessTable = [[  0,  0,  0,  0,  0,  0,  0,  0],
                    [  5, 10, 10, 10, 10, 10, 10,  5],
                    [ -5,  0,  0,  0,  0,  0,  0, -5],
                    [ -5,  0,  5,  5,  5,  5,  0, -5],
                    [ -5,  0,  0,  0,  0,  0,  0, -5],
                    [ -5,  0,  0,  0,  0,  0,  0, -5],
                    [ -5,  0,  0,  0,  0,  0,  0, -5],
                    [  0,  0,  0,  5,  5,  0,  0,  0]];
    default:
      return;
  }
  // late game strategy for king
  if (pieceType === 'k' && numRounds > 20) {
    chessTable = [[-50,-40,-30,-20,-20,-30,-40,-50],
                  [-30,-20,-10,  0,  0,-10,-20,-30],
                  [-30,-10, 20, 30, 30, 20,-10,-30],
                  [-30,-10, 30, 40, 40, 30,-10,-30],
                  [-30,-10, 30, 40, 40, 30,-10,-30],
                  [-30,-10, 20, 30, 30, 20,-10,-30],
                  [-30,-30,  0,  0,  0,  0,-30,-30],
                  [-50,-30,-30,-30,-30,-30,-30,-50]];
  }
  let positionValue = chessTable[i][j];
  if (color === 'b') {
    positionValue = -1 * chessTable[7 - i][7 - j];
  }
  return positionValue;
};

// AI looks for move with lowest total board value
const sumBoardValue = (board, numRounds) => {
  let value = 0;
  for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 8; j++) {
      if (board[i][j]) {
        value += calculatePieceValue(board[i][j].type, board[i][j].color);
        if (['r', 'q'].indexOf(board[i][j].type) === -1) {
          // no special late game strategy for now
          value += calculatePositionValue(board[i][j].type, board[i][j].color, i, j, 10);
        }
      }
    }
  }
  return value;
};

const indexOfMin = (arr) => {
  if (arr.length === 0) {
    return -1;
  }
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
      minIndex = i;
      min = arr[i];
    }
  }
  return minIndex;
};

// sort tuple values from small to large
const sortBySecondElement = (a, b) => {
  if (a[1] === b[1]) {
    return 0;
  }
  return (a[1] < b[1]) ? -1 : 1;
};

const YellowSubsAction = (game, depth) => {
  let valueAfterOnePly = [];
  let possibleMovesBlack = game.moves();

  for (let k = 0; k < possibleMovesBlack.length; k++) {
    game.move(possibleMovesBlack[k]);
    const valueAfterBlackMove = sumBoardValue(game.board());
    valueAfterOnePly.push([possibleMovesBlack[k], valueAfterBlackMove]);
    game.undo();
  }

  valueAfterOnePly.sort(sortBySecondElement);

  let lowestValue = Infinity;
  const whiteMoveValuesOnly = [];
  const whiteMoveAndValue = [];

  for (let s = 0; s < valueAfterOnePly.length; s++) {
    if (valueAfterOnePly[s][1] > lowestValue) {
      break;
    }

    game.move(valueAfterOnePly[s][0]);
    let highestValue = -Infinity;
    // let moveandvalue=[];
    const possibleMovesWhite = game.moves();

    for (let t = 0; t < possibleMovesWhite.length; t++) {
      game.move(possibleMovesWhite[t]);
      const valueAfterWhiteMove = sumBoardValue(game.board());
      if (valueAfterWhiteMove > highestValue) {
        highestValue = valueAfterWhiteMove;
        // moveAndValue = [possibleMovesWhite[t], highestValue];
      }
      game.undo();
    }

    // record best white move value for each black move
    if (highestValue < lowestValue) {
      lowestValue = highestValue;
    }

    whiteMoveValuesOnly.push(highestValue);
    // whiteMoveAndValue.push(moveAndValue);
    game.undo();
  }

  // console.log("best white move for each black move", whiteMoveAndValue);
  const bestBlackMoveIndex = indexOfMin(whiteMoveValuesOnly);
  const bestMove = valueAfterOnePly[bestBlackMoveIndex][0];
  return bestMove;
};

export { YellowSubsAction };
<|endoftext|>


<commit_before>var CheckBoxOption, NonEmptyTextOption, NumberOption, TextOption,
initOptionsPage, importSettings, exportSetting;

Option.saveOptions = function() {
  Option.all.forEach(function(option) {
    option.save();
  });
};

Option.needSaveOptions = function() {
  return !Option.all.every(function(option) {
    return option.areEqual(option.readValueFromElement(), option.previous);
  });
};

NumberOption = (function(_super) {
  __extends(NumberOption, _super);

  function NumberOption() {
    NumberOption.__super__.constructor.apply(this, arguments);
    this.element.addEventListener("input", this.onUpdated);
  }

  NumberOption.prototype.populateElement = function(value) {
    return this.element.value = value;
  };

  NumberOption.prototype.readValueFromElement = function() {
    return parseFloat(this.element.value);
  };

  return NumberOption;

})(Option);

TextOption = (function(_super) {
  __extends(TextOption, _super);

  function TextOption() {
    TextOption.__super__.constructor.apply(this, arguments);
    this.element.addEventListener("input", this.onUpdated);
  }

  TextOption.prototype.populateElement = function(value) {
    return this.element.value = value.replace(/\n /g, '\n\xa0');
  };

  TextOption.prototype.readValueFromElement = function() {
    return this.element.value.trim().replace(/\xa0/g, ' ');
  };

  return TextOption;

})(Option);

NonEmptyTextOption = (function(_super) {
  __extends(NonEmptyTextOption, _super);

  function NonEmptyTextOption() {
    NonEmptyTextOption.__super__.constructor.apply(this, arguments);
  }

  NonEmptyTextOption.prototype.readValueFromElement = function() {
    var value = NonEmptyTextOption.__super__.readValueFromElement.call(this);
    if (value) {
      return value;
    } else {
      bgSettings.set(this.field, bgSettings.defaults[this.field]);
      this.fetch();
      return this.previous;
    }
  };

  return NonEmptyTextOption;

})(TextOption);

CheckBoxOption = (function(_super) {
  __extends(CheckBoxOption, _super);

  function CheckBoxOption() {
    CheckBoxOption.__super__.constructor.apply(this, arguments);
    this.element.addEventListener("change", this.onUpdated);
  }

  CheckBoxOption.prototype.populateElement = function(value) {
    return this.element.checked = value;
  };

  CheckBoxOption.prototype.readValueFromElement = function() {
    return this.element.checked;
  };

  return CheckBoxOption;

})(Option);

initOptionsPage = function() {
  var activateHelpDialog, element, maintainLinkHintsView, name, onUpdated //
    , options, saveOptions, toggleAdvancedOptions, type, _i, _ref, status = 0;

  onUpdated = function() {
    if (status == 1) { return; }
    status = 1;
    var saveBtn = $("saveOptions");
    saveBtn.removeAttribute("disabled");
    saveBtn.innerHTML = "Save Changes";
    $("exportButton").disabled = true;
  };

  maintainLinkHintsView = function() {
    var set = function(el, stat) {
      $(el).parentNode.parentNode.style.display = stat ? "" : "none";
    }, checked = $("filterLinkHints").checked;
    set("linkHintCharacters", !checked);
    set("linkHintNumbers", checked);
  };

  var advancedMode = !bgSettings.get("showAdvancedOptions");
  toggleAdvancedOptions = function(event) {
    if (advancedMode) {
      $("advancedOptions").style.display = "none";
      $("advancedOptionsButton").innerHTML = "Show Advanced Options";
    } else {
      $("advancedOptions").style.display = "";
      $("advancedOptionsButton").innerHTML = "Hide Advanced Options";
    }
    advancedMode = !advancedMode;
    bgSettings.set("showAdvancedOptions", advancedMode);
    $("advancedOptionsButton").blur();
  };

  activateHelpDialog = function(event) {
    var node;
    if (node = $("vimHelpDialog")) {
      node.click();
      DomUtils.suppressEvent(event);
      return;
    }
    MainPort.sendMessage({
      handler: "initHelp",
      unbound: true,
      names: true,
      title: "Command Listing"
    }, MainPort.Listener);
  };

  saveOptions = function() {
    var btn = $("saveOptions");
    if (!btn.disabled) {
      Option.saveOptions();
    }
    btn.disabled = true;
    btn.innerHTML = "No Changes";
    $("exportButton").disabled = false;
    status = 0;
    setTimeout(function () {
      window.onfocus();
      if (Option.syncToFrontend) {
        bgSettings.postUpdate("bufferToLoad", null);
        bgSettings.postUpdate("broadcast", {
          name: "settings",
          load: bgSettings.bufferToLoad
        });
        Option.syncToFrontend = false;
      }
    }, 100);
  };

  $("saveOptions").onclick = saveOptions;
  $("advancedOptionsButton").onclick = toggleAdvancedOptions;
  toggleAdvancedOptions({preventDefault: function() {}});
  $("showCommands").onclick = activateHelpDialog;
  $("filterLinkHints").onclick = maintainLinkHintsView;
  _ref = document.getElementsByClassName("nonEmptyTextOption");
  for (_i = _ref.length; 0 <= --_i; ) {
    element = _ref[_i];
    element.className = element.className + " example info";
    element.innerHTML = "Leave empty to reset this option.";
  }
  maintainLinkHintsView();
  $("settingsFile").onchange = function() {
    var file = this.files[0], reader;
    this.value = "";
    if (!file) { return; }
    reader = new FileReader();
    reader.onload = importSettings;
    reader.readAsText(file);
  };
  $("importButton").onclick = function() {
    $("settingsFile").click();
  };
  $("exportButton").onclick = exportSetting;
  window.onbeforeunload = function() {
    if (status !== 0 && Option.needSaveOptions()) {
      return "You have unsaved changes to options.";
    }
  };
  document.addEventListener("keyup", function(event) {
    if (event.ctrlKey && event.keyCode === 13) {
      if (document.activeElement && document.activeElement.blur) {
        document.activeElement.blur();
      }
      if (status != 0) {
        saveOptions();
      }
    }
  });

  options = {
    exclusionRules: ExclusionRulesOption,
    filterLinkHints: CheckBoxOption,
    hideHud: CheckBoxOption,
    keyMappings: TextOption,
    linkHintCharacters: NonEmptyTextOption,
    linkHintNumbers: NonEmptyTextOption,
    newTabUrl: NonEmptyTextOption,
    nextPatterns: NonEmptyTextOption,
    previousPatterns: NonEmptyTextOption,
    regexFindMode: CheckBoxOption,
    scrollStepSize: NumberOption,
    smoothScroll: CheckBoxOption,
    searchEngines: TextOption,
    searchUrl: NonEmptyTextOption,
    userDefinedCss: TextOption
  };
  for (name in options) {
    type = options[name];
    new type(name, onUpdated);
  }
};

exportSetting = function() {
  var exported_object, exported_data, file_name, force2, d, nodeA;
  exported_object = {name: "Vimium++", time: 0};
  exported_object.__proto__ = null;
  (function() {
    var storage = localStorage, i, len, key, mark_head, all = bgSettings.defaults;
    mark_head = BG.Marks.getMarkKey("");
    for (i = 0, len = storage.length; i < len; i++) {
      key = storage.key(i);
      if (key === "name" || key === "time" || key.startsWith(mark_head)) {
        continue;
      }
      exported_object[key] = (key in all) ? bgSettings.get(key) : storage.getItem(key);
    }
  })();
  delete exported_object.findModeRawQuery;
  d = new Date();
  exported_object.time = d.getTime();
  exported_data = JSON.stringify(exported_object, null, '\t');
  exported_object = null;
  force2 = function(i) { return ((i <= 9) ? '0'  : '') + i; }
  file_name = 'vimium++_' + d.getFullYear() + force2(d.getMonth() + 1) + force2(d.getDate())
    + '_' + force2(d.getHours()) + force2(d.getMinutes()) + force2(d.getSeconds()) + '.json';

  nodeA = document.createElement("a");
  nodeA.download = file_name;
  nodeA.href = "data:application/json;charset=UTF-8," + encodeURIComponent(exported_data);
  nodeA.click();
  console.log("EXPORT settings to", file_name, "at", d);
};

importSettings = function() {
  var new_data;
  try {
    new_data = JSON.parse(this.result);
  } catch (e) {}
  if (!new_data || new_data.name !== "Vimium++" || !(new_data.time > 10000)) {
    VHUD.showForDuration("No settings data found!", 2000);
    return;
  } else if (!confirm(
    "You are loading a settings copy exported at:\n        "
    + new Date(new_data.time - new Date().getTimezoneOffset() * 1000 * 60
      ).toJSON().substring(0, 16).replace('T', ' ')
    + "\n\nAre you sure you want to continue?"
  )) {
    VHUD.showForDuration("You cancelled importing.", 1000);
    return;
  }

  var storage = localStorage, i, key, new_value, func, all = bgSettings.defaults;
  func = function(val) {
    return typeof val !== "string" ? val : val.substring(0, 72);
  };
  console.log("IMPORT settings at", new Date(new_data.time));
  delete new_data.name;
  delete new_data.time;
  delete new_data.findModeRawQuery;
  for (i = storage.length; 0 <= --i; ) {
    key = storage.key(i);
    if (!(key in new_data)) {
      new_data[key] = null;
    }
  }
  Option.all.forEach(function(item) {
    var key = item.field, new_value = new_data[key];
    delete new_data[key];
    if (new_value == null) {
      new_value = all[key];
    }
    if (!item.areEqual(bgSettings.get(key), new_value)) {
      console.log("import", key, func(new_value));
      bgSettings.set(key, new_value);
    }
    item.fetch();
  });
  for (key in new_data) {
    new_value = new_data[key];
    if (new_value == null) {
      if (key in all) {
        new_value = all[key];
        if (bgSettings.get(key) !== new_value) {
          bgSettings.set(key, new_value);
          console.log("reset", key, func(new_value));
          continue;
        }
        new_value = bgSettings.get(key);
      } else {
        new_value = storage.getItem(key);
      }
      storage.removeItem(key);
      console.log("remove", key, "<=", func(new_value));
    } else if (key in all) {
      if (bgSettings.get(key) !== new_value) {
        bgSettings.set(key, new_value);
        console.log("update", key, func(new_value));
      }
    } else {
      storage.setItem(key, new_value);
      console.log("save", key, func(new_value));
    }
  }
  var btn = $("saveOptions");
  btn.disabled = true;
  btn.click();
  VHUD.showForDuration("Import settings data: OK!", 1000);
};
<commit_msg>options page: fix a bug that "Show available commands" fails when a common help dialog is showing<commit_after>var CheckBoxOption, NonEmptyTextOption, NumberOption, TextOption,
initOptionsPage, importSettings, exportSetting;

Option.saveOptions = function() {
  Option.all.forEach(function(option) {
    option.save();
  });
};

Option.needSaveOptions = function() {
  return !Option.all.every(function(option) {
    return option.areEqual(option.readValueFromElement(), option.previous);
  });
};

NumberOption = (function(_super) {
  __extends(NumberOption, _super);

  function NumberOption() {
    NumberOption.__super__.constructor.apply(this, arguments);
    this.element.addEventListener("input", this.onUpdated);
  }

  NumberOption.prototype.populateElement = function(value) {
    return this.element.value = value;
  };

  NumberOption.prototype.readValueFromElement = function() {
    return parseFloat(this.element.value);
  };

  return NumberOption;

})(Option);

TextOption = (function(_super) {
  __extends(TextOption, _super);

  function TextOption() {
    TextOption.__super__.constructor.apply(this, arguments);
    this.element.addEventListener("input", this.onUpdated);
  }

  TextOption.prototype.populateElement = function(value) {
    return this.element.value = value.replace(/\n /g, '\n\xa0');
  };

  TextOption.prototype.readValueFromElement = function() {
    return this.element.value.trim().replace(/\xa0/g, ' ');
  };

  return TextOption;

})(Option);

NonEmptyTextOption = (function(_super) {
  __extends(NonEmptyTextOption, _super);

  function NonEmptyTextOption() {
    NonEmptyTextOption.__super__.constructor.apply(this, arguments);
  }

  NonEmptyTextOption.prototype.readValueFromElement = function() {
    var value = NonEmptyTextOption.__super__.readValueFromElement.call(this);
    if (value) {
      return value;
    } else {
      bgSettings.set(this.field, bgSettings.defaults[this.field]);
      this.fetch();
      return this.previous;
    }
  };

  return NonEmptyTextOption;

})(TextOption);

CheckBoxOption = (function(_super) {
  __extends(CheckBoxOption, _super);

  function CheckBoxOption() {
    CheckBoxOption.__super__.constructor.apply(this, arguments);
    this.element.addEventListener("change", this.onUpdated);
  }

  CheckBoxOption.prototype.populateElement = function(value) {
    return this.element.checked = value;
  };

  CheckBoxOption.prototype.readValueFromElement = function() {
    return this.element.checked;
  };

  return CheckBoxOption;

})(Option);

initOptionsPage = function() {
  var activateHelpDialog, element, maintainLinkHintsView, name, onUpdated //
    , options, saveOptions, toggleAdvancedOptions, type, _i, _ref, status = 0;

  onUpdated = function() {
    if (status == 1) { return; }
    status = 1;
    var saveBtn = $("saveOptions");
    saveBtn.removeAttribute("disabled");
    saveBtn.innerHTML = "Save Changes";
    $("exportButton").disabled = true;
  };

  maintainLinkHintsView = function() {
    var set = function(el, stat) {
      $(el).parentNode.parentNode.style.display = stat ? "" : "none";
    }, checked = $("filterLinkHints").checked;
    set("linkHintCharacters", !checked);
    set("linkHintNumbers", checked);
  };

  var advancedMode = !bgSettings.get("showAdvancedOptions");
  toggleAdvancedOptions = function(event) {
    if (advancedMode) {
      $("advancedOptions").style.display = "none";
      $("advancedOptionsButton").innerHTML = "Show Advanced Options";
    } else {
      $("advancedOptions").style.display = "";
      $("advancedOptionsButton").innerHTML = "Hide Advanced Options";
    }
    advancedMode = !advancedMode;
    bgSettings.set("showAdvancedOptions", advancedMode);
    $("advancedOptionsButton").blur();
  };

  activateHelpDialog = function(event) {
    var node;
    DomUtils.suppressEvent(event);
    if (node = document.querySelector('.vimHelpCommandName')) {
      node.click();
      return;
    }
    MainPort.sendMessage({
      handler: "initHelp",
      unbound: true,
      names: true,
      title: "Command Listing"
    }, function(response) {
      if (node = $("vimHelpDialog")) {
        MainPort.Listener({
          name: "executePageCommand",
          command: "showHelp",
          count: 1
        });
      }
      MainPort.Listener(response);
    });
  };

  saveOptions = function() {
    var btn = $("saveOptions");
    if (!btn.disabled) {
      Option.saveOptions();
    }
    btn.disabled = true;
    btn.innerHTML = "No Changes";
    $("exportButton").disabled = false;
    status = 0;
    setTimeout(function () {
      window.onfocus();
      if (Option.syncToFrontend) {
        bgSettings.postUpdate("bufferToLoad", null);
        bgSettings.postUpdate("broadcast", {
          name: "settings",
          load: bgSettings.bufferToLoad
        });
        Option.syncToFrontend = false;
      }
    }, 100);
  };

  $("saveOptions").onclick = saveOptions;
  $("advancedOptionsButton").onclick = toggleAdvancedOptions;
  toggleAdvancedOptions({preventDefault: function() {}});
  $("showCommands").onclick = activateHelpDialog;
  $("filterLinkHints").onclick = maintainLinkHintsView;
  _ref = document.getElementsByClassName("nonEmptyTextOption");
  for (_i = _ref.length; 0 <= --_i; ) {
    element = _ref[_i];
    element.className = element.className + " example info";
    element.innerHTML = "Leave empty to reset this option.";
  }
  maintainLinkHintsView();
  $("settingsFile").onchange = function() {
    var file = this.files[0], reader;
    this.value = "";
    if (!file) { return; }
    reader = new FileReader();
    reader.onload = importSettings;
    reader.readAsText(file);
  };
  $("importButton").onclick = function() {
    $("settingsFile").click();
  };
  $("exportButton").onclick = exportSetting;
  window.onbeforeunload = function() {
    if (status !== 0 && Option.needSaveOptions()) {
      return "You have unsaved changes to options.";
    }
  };
  document.addEventListener("keyup", function(event) {
    if (event.ctrlKey && event.keyCode === 13) {
      if (document.activeElement && document.activeElement.blur) {
        document.activeElement.blur();
      }
      if (status != 0) {
        saveOptions();
      }
    }
  });

  options = {
    exclusionRules: ExclusionRulesOption,
    filterLinkHints: CheckBoxOption,
    hideHud: CheckBoxOption,
    keyMappings: TextOption,
    linkHintCharacters: NonEmptyTextOption,
    linkHintNumbers: NonEmptyTextOption,
    newTabUrl: NonEmptyTextOption,
    nextPatterns: NonEmptyTextOption,
    previousPatterns: NonEmptyTextOption,
    regexFindMode: CheckBoxOption,
    scrollStepSize: NumberOption,
    smoothScroll: CheckBoxOption,
    searchEngines: TextOption,
    searchUrl: NonEmptyTextOption,
    userDefinedCss: TextOption
  };
  for (name in options) {
    type = options[name];
    new type(name, onUpdated);
  }
};

exportSetting = function() {
  var exported_object, exported_data, file_name, force2, d, nodeA;
  exported_object = {name: "Vimium++", time: 0};
  exported_object.__proto__ = null;
  (function() {
    var storage = localStorage, i, len, key, mark_head, all = bgSettings.defaults;
    mark_head = BG.Marks.getMarkKey("");
    for (i = 0, len = storage.length; i < len; i++) {
      key = storage.key(i);
      if (key === "name" || key === "time" || key.startsWith(mark_head)) {
        continue;
      }
      exported_object[key] = (key in all) ? bgSettings.get(key) : storage.getItem(key);
    }
  })();
  delete exported_object.findModeRawQuery;
  d = new Date();
  exported_object.time = d.getTime();
  exported_data = JSON.stringify(exported_object, null, '\t');
  exported_object = null;
  force2 = function(i) { return ((i <= 9) ? '0'  : '') + i; }
  file_name = 'vimium++_' + d.getFullYear() + force2(d.getMonth() + 1) + force2(d.getDate())
    + '_' + force2(d.getHours()) + force2(d.getMinutes()) + force2(d.getSeconds()) + '.json';

  nodeA = document.createElement("a");
  nodeA.download = file_name;
  nodeA.href = "data:application/json;charset=UTF-8," + encodeURIComponent(exported_data);
  nodeA.click();
  console.log("EXPORT settings to", file_name, "at", d);
};

importSettings = function() {
  var new_data;
  try {
    new_data = JSON.parse(this.result);
  } catch (e) {}
  if (!new_data || new_data.name !== "Vimium++" || !(new_data.time > 10000)) {
    VHUD.showForDuration("No settings data found!", 2000);
    return;
  } else if (!confirm(
    "You are loading a settings copy exported at:\n        "
    + new Date(new_data.time - new Date().getTimezoneOffset() * 1000 * 60
      ).toJSON().substring(0, 16).replace('T', ' ')
    + "\n\nAre you sure you want to continue?"
  )) {
    VHUD.showForDuration("You cancelled importing.", 1000);
    return;
  }

  var storage = localStorage, i, key, new_value, func, all = bgSettings.defaults;
  func = function(val) {
    return typeof val !== "string" ? val : val.substring(0, 72);
  };
  console.log("IMPORT settings at", new Date(new_data.time));
  delete new_data.name;
  delete new_data.time;
  delete new_data.findModeRawQuery;
  for (i = storage.length; 0 <= --i; ) {
    key = storage.key(i);
    if (!(key in new_data)) {
      new_data[key] = null;
    }
  }
  Option.all.forEach(function(item) {
    var key = item.field, new_value = new_data[key];
    delete new_data[key];
    if (new_value == null) {
      new_value = all[key];
    }
    if (!item.areEqual(bgSettings.get(key), new_value)) {
      console.log("import", key, func(new_value));
      bgSettings.set(key, new_value);
    }
    item.fetch();
  });
  for (key in new_data) {
    new_value = new_data[key];
    if (new_value == null) {
      if (key in all) {
        new_value = all[key];
        if (bgSettings.get(key) !== new_value) {
          bgSettings.set(key, new_value);
          console.log("reset", key, func(new_value));
          continue;
        }
        new_value = bgSettings.get(key);
      } else {
        new_value = storage.getItem(key);
      }
      storage.removeItem(key);
      console.log("remove", key, "<=", func(new_value));
    } else if (key in all) {
      if (bgSettings.get(key) !== new_value) {
        bgSettings.set(key, new_value);
        console.log("update", key, func(new_value));
      }
    } else {
      storage.setItem(key, new_value);
      console.log("save", key, func(new_value));
    }
  }
  var btn = $("saveOptions");
  btn.disabled = true;
  btn.click();
  VHUD.showForDuration("Import settings data: OK!", 1000);
};
<|endoftext|>


<commit_before>// @flow
import React from 'react'
import Card from './Card'
import {Container} from 'reactstrap'
import SearchAutocomplete from '../Search/SearchAutocomplete'
import publicDataIcon from './icons/public_data.png'
import prepojeniaIcon from './icons/prepojenia.png'
import obstaravaniaIcon from './icons/obstaravania.png'
import profilyIcon from './icons/profily.png'
import './Landing.css'

const Landing = () => (

    <Container tag="main" role="main" className="landing-container">

            verejne.digital

            Aplikácie umelej inteligencie

 na dáta slovenských verejných inštitúcií

      <SearchAutocomplete />

        <Card
          to="/verejne"
          title="Mapa"
          text="Obchodujú moji susedia alebo obchodní partneri so štátom?"
          imgSrc={publicDataIcon}
        />
        <Card
          to="/profil"
          title="Profil"
          text="Majetok verejných funkcionárov podľa priznaní a katastra."
          imgSrc={profilyIcon}
        />
        <Card
          to="/prepojenia"
          title="Prepojenia"
          text="Aké sú vzťahy medzi firmami a osobami?"
          imgSrc={prepojeniaIcon}
        />
        <Card
          to="/obstaravania"
          title="Obstarávania"
          text="Do ktorých výziev sa prihlásiť a ktoré sú podozrivé?"
          imgSrc={obstaravaniaIcon}
        />
        <Card
          to="/ihrisko"
          title="Ihrisko"
          text="Hrajte sa s našimi dátami!"
          imgSrc={obstaravaniaIcon}
          beta
        />

    </Container>

      <Container>

                O projekte

                Kontaktujte nás cez facebook

          Prevádzkovateľ

          Partneri

      </Container>

)

export default Landing
<commit_msg>zmena ihriska na landing page<commit_after>// @flow
import React from 'react'
import Card from './Card'
import {Container} from 'reactstrap'
import SearchAutocomplete from '../Search/SearchAutocomplete'
import publicDataIcon from './icons/public_data.png'
import prepojeniaIcon from './icons/prepojenia.png'
import obstaravaniaIcon from './icons/obstaravania.png'
import profilyIcon from './icons/profily.png'
import ihriskoIcon from './icons/ihrisko.png'
import './Landing.css'

const Landing = () => (

    <Container tag="main" role="main" className="landing-container">

            verejne.digital

            Aplikácie umelej inteligencie

 na dáta slovenských verejných inštitúcií

      <SearchAutocomplete />

        <Card
          to="/verejne"
          title="Mapa"
          text="Obchodujú moji susedia alebo obchodní partneri so štátom?"
          imgSrc={publicDataIcon}
        />
        <Card
          to="/profil"
          title="Profil"
          text="Majetok verejných funkcionárov podľa priznaní a katastra."
          imgSrc={profilyIcon}
        />
        <Card
          to="/prepojenia"
          title="Prepojenia"
          text="Aké sú vzťahy medzi firmami a osobami?"
          imgSrc={prepojeniaIcon}
        />
        <Card
          to="/obstaravania"
          title="Obstarávania"
          text="Do ktorých výziev sa prihlásiť a ktoré sú podozrivé?"
          imgSrc={obstaravaniaIcon}
        />
        <Card
          to="/ihrisko"
          title="Ihrisko"
          text="Hrajte sa s našimi dátami!"
          imgSrc={ihriskoIcon}
          beta
        />

    </Container>

      <Container>

                O projekte

                Kontaktujte nás cez facebook

          Prevádzkovateľ

          Partneri

      </Container>

)

export default Landing
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {Table} from 'react-bootstrap';

import Helmet from 'react-helmet';

import {connect} from 'react-redux';
import math from 'mathjs';
import moment from 'moment';

import * as workerActions from '../../redux/modules/workers';

function convertSize(sizeB) {
  const units = [
    'B',
    'kB',
    'MB',
    'GB'
  ];

  let i = 0;
  let res = sizeB;
  while (res >= 1024 && (i + 1 < units.length)) {
    res /= 1024;
    i += 1;
  }

  return `${math.round(res, 2)} ${units[i]}`;
}

@connect(
  (state) => ({
    workers: state.workers
  }),
  {
    ...workerActions
  }
)
export default class Workers extends Component {
  static propTypes = {
    workers: PropTypes.object
  };

  render() {
    const workers = (this.props.workers && this.props.workers.workers) || [];

    return (

        <Helmet title="Workers" />

Workers

              UUID
              Platform
              Hostname
              Booted
              CPU
              Load
              Memory

            {workers.map((worker) => {
              return (

                  {worker.join.uuid}
                  {worker.ping && worker.ping.os.platform}
                  {worker.ping && worker.ping.os.hostname}
                  {worker.ping && moment.utc(new Date(new Date().getTime() - (worker.ping.os.uptime * 1000))).fromNow()}
                  {worker.ping && worker.ping.os.cpus.length} x {worker.ping && worker.ping.os.cpus[0].model}
                  {worker.ping && worker.ping.os.load.map(x => { return x.toFixed(2); }).join(', ')}
                  {worker.ping && convertSize(worker.ping.os.mem.free)} / {worker.ping && convertSize(worker.ping.os.mem.total)}

              );
            })}

    );
  }
}
<commit_msg>Add country flag<commit_after>import React, {Component, PropTypes} from 'react';
import {Table} from 'react-bootstrap';

import Helmet from 'react-helmet';

import {connect} from 'react-redux';
import math from 'mathjs';
import moment from 'moment';

import * as workerActions from '../../redux/modules/workers';

function convertSize(sizeB) {
  const units = [
    'B',
    'kB',
    'MB',
    'GB'
  ];

  let i = 0;
  let res = sizeB;
  while (res >= 1024 && (i + 1 < units.length)) {
    res /= 1024;
    i += 1;
  }

  return `${math.round(res, 2)} ${units[i]}`;
}

@connect(
  (state) => ({
    workers: state.workers
  }),
  {
    ...workerActions
  }
)
export default class Workers extends Component {
  static propTypes = {
    workers: PropTypes.object
  };

  render() {
    const workers = (this.props.workers && this.props.workers.workers) || [];

    return (

        <Helmet title="Workers" />

Workers

              UUID
              Country
              Platform
              Hostname
              Booted
              CPU
              Load
              Memory

            {workers.map((worker) => {
              return (

                  {worker.join.uuid}

                  {worker.ping && worker.ping.os.platform}
                  {worker.ping && worker.ping.os.hostname}
                  {worker.ping && moment.utc(new Date(new Date().getTime() - (worker.ping.os.uptime * 1000))).fromNow()}
                  {worker.ping && worker.ping.os.cpus.length} x {worker.ping && worker.ping.os.cpus[0].model}
                  {worker.ping && worker.ping.os.load.map(x => { return x.toFixed(2); }).join(', ')}
                  {worker.ping && convertSize(worker.ping.os.mem.free)} / {worker.ping && convertSize(worker.ping.os.mem.total)}

              );
            })}

    );
  }
}
<|endoftext|>


<commit_before>import { $ } from 'meteor/jquery';
import { Template } from 'meteor/templating';
import History from './history';

/**
 * @summary Smooth scroll to a linked section
 * @method
 *   @param {string} path - Element ID to scroll to
 */
const smoothScroll = (path) => {
  // Get rid of leading slashes and any sub paths
  const newPath = path.replace(/^\/*/, '').replace(/\/.*/g, '');

  // Get target element (that the anchor links to)
  // Otherwise, default to top of screen
  const target = newPath ? $(`[id="${newPath}"]`) : $('body');

  // If no target, don't bother
  if (!target.length) return;

  // Where are we presently?
  const posY = window.scrollY;

  // Calculate target Y offset
  const offset = target.offset().top - 96;

  // We want to scroll at 750 pixels per second
  const speed = Math.abs(posY - offset);

  // Smooth scroll to target
  $('.mainNav li a').removeClass('active');

  // http://stackoverflow.com/questions/8149155/animate-scrolltop-not-working-in-firefox
  $('body,html').stop(true, true)
    .animate({ scrollTop: offset }, speed > 750 ? 750 : speed);
};

/**
 * @summary Handle anchor click event to smooth scroll
 * @method
 *   @param {$.Event} event - jQuery Event triggered by <a> element click
 */
const smoothScrollEventHandler = (event) => {
  // Don't allow page to navigate away
  event.preventDefault();
  event.stopPropagation();

  // Smooth scroll to anchor's href destination
  History.navigate(event.currentTarget.pathname);
};

/**
 * @summary Timout in milliseconds to wait until scroll completion
 * @type {number}
 */
let timeout = 0;

/**
 * @summary Handle Header state change on scroll
 * @method
 *   @param {$.Event} event - jQuery Scroll event triggered by user scroll
 */
const handleHeaderStateChange = () => {
  // Why we're using timers here:
  // The scroll event will fire for every pixel (or browser/OS-specific unit)
  // scrolled, causing major performance issues, especially when interacting
  // with the DOM as we do here by adding and removing classes.
  //
  // Instead, we use timeouts to wait for a scroll to complete before executing
  // CPU-intensive code.  For each time the event fires, the timeout is cleared,
  // essentially causing the code to wait until the event is fired for its
  // last time.

  // Clear the timeout
  clearTimeout(timeout);

  // Set a timeout to add the class after one millisecond
  timeout = setTimeout(() => {
    if (window.scrollY > 260 && window.innerWidth > 767) {
      document.body.classList.remove('fixedHeaderReturn');
      document.body.classList.add('fixedHeader');
    } else {
      document.body.classList.remove('fixedHeader');
      document.body.classList.add('fixedHeaderReturn');
    }

    // Back to Top
    // TODO(eoghantadhg): move this into appropriate module
    if (document.getElementById('back-to-top')) {
      if (window.scrollY > 1000 && window.innerWidth > 767) {
        document.getElementById('back-to-top').classList.add('active');
      } else document.getElementById('back-to-top').classList.remove('active');
    }
  }, 1);
};

// Handle header state change
Template.canvas.onRendered(() => window.addEventListener('scroll', handleHeaderStateChange));

export { smoothScroll, smoothScrollEventHandler };
<commit_msg>Improved scroll performance<commit_after>import { $ } from 'meteor/jquery';
import { Template } from 'meteor/templating';
import History from './history';

/**
 * @summary Smooth scroll to a linked section
 * @method
 *   @param {string} path - Element ID to scroll to
 */
const smoothScroll = (path) => {
  // Get rid of leading slashes and any sub paths
  const newPath = path.replace(/^\/*/, '').replace(/\/.*/g, '');

  // Get target element (that the anchor links to)
  // Otherwise, default to top of screen
  const target = newPath ? $(`[id="${newPath}"]`) : $('body');

  // If no target, don't bother
  if (!target.length) return;

  // Where are we presently?
  const posY = window.scrollY;

  // Calculate target Y offset
  const offset = target.offset().top - 96;

  // We want to scroll at 750 pixels per second
  const speed = Math.abs(posY - offset);

  // Smooth scroll to target
  $('.mainNav li a').removeClass('active');

  // http://stackoverflow.com/questions/8149155/animate-scrolltop-not-working-in-firefox
  $('body,html').stop(true, true)
    .animate({ scrollTop: offset }, speed > 750 ? 750 : speed);
};

/**
 * @summary Handle anchor click event to smooth scroll
 * @method
 *   @param {$.Event} event - jQuery Event triggered by <a> element click
 */
const smoothScrollEventHandler = (event) => {
  // Don't allow page to navigate away
  event.preventDefault();
  event.stopPropagation();

  // Smooth scroll to anchor's href destination
  History.navigate(event.currentTarget.pathname);
};

/**
 * @summary Timout in milliseconds to wait until scroll completion
 * @type {number}
 */
let timeout = 0;

/**
 * @summary Handle Header state change on scroll
 * @method
 *   @param {$.Event} event - jQuery Scroll event triggered by user scroll
 */
const handleHeaderStateChange = () => {
  // Why we're using timers here:
  // The scroll event will fire for every pixel (or browser/OS-specific unit)
  // scrolled, causing major performance issues, especially when interacting
  // with the DOM as we do here by adding and removing classes.
  //
  // Instead, we use timeouts to wait for a scroll to complete before executing
  // CPU-intensive code.  For each time the event fires, the timeout is cleared,
  // essentially causing the code to wait until the event is fired for its
  // last time.

  // Clear the timeout
  clearTimeout(timeout);

  // Set a timeout to add the class after one millisecond
  timeout = setTimeout(() => {
    // Read style calculations before writing to avoid forced synchronous layout
    // @link https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts
    const { scrollY, innerWidth } = window;
    if (scrollY > 260 && innerWidth > 767) {
      document.body.classList.remove('fixedHeaderReturn');
      document.body.classList.add('fixedHeader');
    } else {
      document.body.classList.remove('fixedHeader');
      document.body.classList.add('fixedHeaderReturn');
    }

    // Back to Top
    // TODO(eoghantadhg): move this into appropriate module
    if (document.getElementById('back-to-top')) {
      if (scrollY > 1000 && innerWidth > 767) {
        document.getElementById('back-to-top').classList.add('active');
      } else document.getElementById('back-to-top').classList.remove('active');
    }
  }, 1);
};

// Handle header state change
Template.canvas.onRendered(() => window.addEventListener('scroll', handleHeaderStateChange));

export { smoothScroll, smoothScrollEventHandler };
<|endoftext|>


<commit_before><commit_msg>Removed "use strict" statement<commit_after><|endoftext|>


<commit_before><commit_msg>Add save user method<commit_after><|endoftext|>


<commit_before>var gulp            = require('gulp'),
    plugins         = require('gulp-load-plugins')(),
    nib             = require('nib'),
    browserify      = require('browserify'),
    source          = require('vinyl-source-stream'),
    buffer          = require('vinyl-buffer'),
    del             = require('del')

gulp.task('clean:js', function(cb) {
    del(['dist/*.js'], cb)
})

gulp.task('stylus', function() {
    gulp.src('src/assets/styl/main.styl')
        .pipe(plugins.plumber()) // with the plumber the gulp task won't crash on errors
        .pipe(plugins.stylus({
            use:    [nib()],
            errors: true
        }))
        // https://github.com/ai/autoprefixer#browsers
        .pipe(plugins.autoprefixer(
            'last 3 versions',
            '> 1%',
            'Explorer >= 9',
            'Chrome >= 30',
            'Firefox ESR',
            'iOS >= 6', 'android >= 4'
        ))
        .pipe(plugins.minifyCss())
        .pipe(plugins.rename({suffix: '.min', extname: '.css.js'}))
        .pipe(plugins.injectString.wrap('module.exports=\'', '\''))
        .pipe(gulp.dest('src/assets/css'))
        .pipe(plugins.connect.reload())
})

gulp.task('todo', function() {
    gulp.src('src/**/*.{js, styl}', {base: './'})
        .pipe(plugins.todo({
            fileName: 'TODO.md'
        }))
        .pipe(gulp.dest('./'))
})

gulp.task('browserify', ['clean:js'], function(cb) {
    var bundler = browserify({
            entries:    ['./src/index.js'],
            globals:    false,
            debug:      true // enables source maps
        })

    bundler
        .require('./src/index.js', {expose: 'videomail-client'})
        .bundle()
        .on('error',    cb)
        .on('log',      plugins.util.log)
        .pipe(source('./src/')) // gives streaming vinyl file object
        .pipe(buffer()) // required because the next steps do not support streams
        .pipe(plugins.concat('videomail-client.js'))
        .pipe(gulp.dest('dist'))
        /* TODO: add this back when we are stable. commented out now for speed.
        .pipe(plugins.rename({suffix: '.min'}))
        .pipe(plugins.uglify())
        .pipe(gulp.dest('dist'))
        */
        .pipe(plugins.connect.reload())
        .on('end', cb)
})

gulp.task('connect', ['build'], function() {
    plugins.connect.server({
        root:       ['examples', 'dist'],
        port:       8080,
        livereload: true
    })
})

gulp.task('reload', function() {
    plugins.connect.reload()
})

gulp.task('watch', ['connect'], function() {
    gulp.watch(['src/assets/styl/**/*.styl'],   ['stylus'])
    gulp.watch(['src/**/*.js'],                 ['browserify'])
    gulp.watch(['examples/*.html'],             ['reload'])
})

gulp.task('examples',  ['connect', 'watch'])
gulp.task('build',     ['stylus', 'browserify'])
gulp.task('default',   ['stylus', 'browserify', 'todo'])
<commit_msg>Include gulp todo into gulp build<commit_after>var gulp            = require('gulp'),
    plugins         = require('gulp-load-plugins')(),
    nib             = require('nib'),
    browserify      = require('browserify'),
    source          = require('vinyl-source-stream'),
    buffer          = require('vinyl-buffer'),
    del             = require('del')

gulp.task('clean:js', function(cb) {
    del(['dist/*.js'], cb)
})

gulp.task('stylus', function() {
    gulp.src('src/assets/styl/main.styl')
        .pipe(plugins.plumber()) // with the plumber the gulp task won't crash on errors
        .pipe(plugins.stylus({
            use:    [nib()],
            errors: true
        }))
        // https://github.com/ai/autoprefixer#browsers
        .pipe(plugins.autoprefixer(
            'last 3 versions',
            '> 1%',
            'Explorer >= 9',
            'Chrome >= 30',
            'Firefox ESR',
            'iOS >= 6', 'android >= 4'
        ))
        .pipe(plugins.minifyCss())
        .pipe(plugins.rename({suffix: '.min', extname: '.css.js'}))
        .pipe(plugins.injectString.wrap('module.exports=\'', '\''))
        .pipe(gulp.dest('src/assets/css'))
        .pipe(plugins.connect.reload())
})

gulp.task('todo', function() {
    gulp.src('src/**/*.{js, styl}', {base: './'})
        .pipe(plugins.todo({
            fileName: 'TODO.md'
        }))
        .pipe(gulp.dest('./'))
})

gulp.task('browserify', ['clean:js'], function(cb) {
    var bundler = browserify({
            entries:    ['./src/index.js'],
            globals:    false,
            debug:      true // enables source maps
        })

    bundler
        .require('./src/index.js', {expose: 'videomail-client'})
        .bundle()
        .on('error',    cb)
        .on('log',      plugins.util.log)
        .pipe(source('./src/')) // gives streaming vinyl file object
        .pipe(buffer()) // required because the next steps do not support streams
        .pipe(plugins.concat('videomail-client.js'))
        .pipe(gulp.dest('dist'))
        /* TODO: add this back when we are stable. commented out now for speed.
        .pipe(plugins.rename({suffix: '.min'}))
        .pipe(plugins.uglify())
        .pipe(gulp.dest('dist'))
        */
        .pipe(plugins.connect.reload())
        .on('end', cb)
})

gulp.task('connect', ['build'], function() {
    plugins.connect.server({
        root:       ['examples', 'dist'],
        port:       8080,
        livereload: true
    })
})

gulp.task('reload', function() {
    plugins.connect.reload()
})

gulp.task('watch', ['connect'], function() {
    gulp.watch(['src/assets/styl/**/*.styl'],   ['stylus'])
    gulp.watch(['src/**/*.js'],                 ['browserify'])
    gulp.watch(['examples/*.html'],             ['reload'])
})

gulp.task('examples',  ['connect', 'watch'])
gulp.task('build',     ['stylus', 'browserify', 'todo'])
gulp.task('default',   ['build'])
<|endoftext|>


<commit_before>const babel            = require('gulp-babel');
const createTestCafe   = require('testcafe');
const del              = require('del');
const eslint           = require('gulp-eslint-new');
const fs               = require('fs');
const glob             = require('glob');
const gulp             = require('gulp');
const mustache         = require('gulp-mustache');
const pathJoin         = require('path').join;
const rename           = require('gulp-rename');
const startTestServer  = require('./test/server');
const { promisify }    = require('util');
const nextBuild        = require('next/dist/build').default;
const { createServer } = require('vite');

const listFiles   = promisify(glob);
const deleteFiles = promisify(del);

let devServer   = null;

gulp.task('clean', () => {
    return deleteFiles([
        'lib',
        'test/data/lib'
    ]);
});

gulp.task('lint', () => {
    return gulp
        .src([
            'src/**/*.js',
            'test/**/*.js',
            '!test/data/**',
            'Gulpfile.js'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('build-selectors-script', () => {
    function loadModule (modulePath) {
        return fs.readFileSync(modulePath).toString();
    }

    return gulp.src('./src/index.js.mustache')
        .pipe(mustache({
            getRootElsReact15:     loadModule('./src/react-15/get-root-els.js'),
            getRootElsReact16to18: loadModule('./src/react-16-18/get-root-els.js'),

            selectorReact15:     loadModule('./src/react-15/index.js'),
            selectorReact16to18: loadModule('./src/react-16-18/index.js'),

            react15Utils:     loadModule('./src/react-15/react-utils.js'),
            react16to18Utils: loadModule('./src/react-16-18/react-utils.js'),

            waitForReact: loadModule('./src/wait-for-react.js')
        }))
        .pipe(rename('index.js'))
        .pipe(gulp.dest('lib'));
});

gulp.task('transpile', () => {
    return gulp
        .src('lib/tmp/**/*.js')
        .pipe(babel({ extends: pathJoin(__dirname, './src/.babelrc') }))
        .pipe(gulp.dest('lib'));
});

gulp.task('clean-build-tmp-resources', () => {
    return deleteFiles(['lib/tmp']);
});

gulp.task('build-nextjs-app', () => {
    const appPath = pathJoin(__dirname, './test/data/server-render');

    return nextBuild(appPath, require('./next.config.js'));
});

gulp.task('build', gulp.series('clean', 'lint', 'build-selectors-script', /* 'transpile',*/ 'clean-build-tmp-resources'));

gulp.task('start-dev-server', async () => {
    const src = 'test/data/app';

    devServer = await createServer({
        configFile: false,
        root:       src,

        server: {
            port: 3000
        }
    });

    await devServer.listen();
});

gulp.task('run-tests', async cb => {
    const files = await listFiles('test/fixtures/**/*.{js,ts}');

    await startTestServer();

    const testCafe = await createTestCafe('localhost', 1337, 1338);

    await testCafe.createRunner()
        .src(files)
        .browsers(['chrome', 'firefox', 'ie'])
        .reporter('list')
        .run({ quarantineMode: false, debugOnFail: true })
        .then(failed => {
            devServer.close();

            cb();
            process.exit(failed);
        });
});

gulp.task('test', gulp.series('build', 'start-dev-server', 'build-nextjs-app', 'run-tests'));
<commit_msg>change run options<commit_after>const babel            = require('gulp-babel');
const createTestCafe   = require('testcafe');
const del              = require('del');
const eslint           = require('gulp-eslint-new');
const fs               = require('fs');
const glob             = require('glob');
const gulp             = require('gulp');
const mustache         = require('gulp-mustache');
const pathJoin         = require('path').join;
const rename           = require('gulp-rename');
const startTestServer  = require('./test/server');
const { promisify }    = require('util');
const nextBuild        = require('next/dist/build').default;
const { createServer } = require('vite');

const listFiles   = promisify(glob);
const deleteFiles = promisify(del);

let devServer   = null;

gulp.task('clean', () => {
    return deleteFiles([
        'lib',
        'test/data/lib'
    ]);
});

gulp.task('lint', () => {
    return gulp
        .src([
            'src/**/*.js',
            'test/**/*.js',
            '!test/data/**',
            'Gulpfile.js'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('build-selectors-script', () => {
    function loadModule (modulePath) {
        return fs.readFileSync(modulePath).toString();
    }

    return gulp.src('./src/index.js.mustache')
        .pipe(mustache({
            getRootElsReact15:     loadModule('./src/react-15/get-root-els.js'),
            getRootElsReact16to18: loadModule('./src/react-16-18/get-root-els.js'),

            selectorReact15:     loadModule('./src/react-15/index.js'),
            selectorReact16to18: loadModule('./src/react-16-18/index.js'),

            react15Utils:     loadModule('./src/react-15/react-utils.js'),
            react16to18Utils: loadModule('./src/react-16-18/react-utils.js'),

            waitForReact: loadModule('./src/wait-for-react.js')
        }))
        .pipe(rename('index.js'))
        .pipe(gulp.dest('lib'));
});

gulp.task('transpile', () => {
    return gulp
        .src('lib/tmp/**/*.js')
        .pipe(babel({ extends: pathJoin(__dirname, './src/.babelrc') }))
        .pipe(gulp.dest('lib'));
});

gulp.task('clean-build-tmp-resources', () => {
    return deleteFiles(['lib/tmp']);
});

gulp.task('build-nextjs-app', () => {
    const appPath = pathJoin(__dirname, './test/data/server-render');

    return nextBuild(appPath, require('./next.config.js'));
});

gulp.task('build', gulp.series('clean', 'lint', 'build-selectors-script', /* 'transpile',*/ 'clean-build-tmp-resources'));

gulp.task('start-dev-server', async () => {
    const src = 'test/data/app';

    devServer = await createServer({
        configFile: false,
        root:       src,

        server: {
            port: 3000
        }
    });

    await devServer.listen();
});

gulp.task('run-tests', async cb => {
    const files = await listFiles('test/fixtures/**/*.{js,ts}');

    await startTestServer();

    const testCafe = await createTestCafe('localhost', 1337, 1338);

    await testCafe.createRunner()
        .src(files)
        .browsers(['chrome', 'firefox', 'ie'])
        .reporter('list')
        .run({ quarantineMode: true, debugOnFail: false })
        .then(failed => {
            devServer.close();

            cb();
            process.exit(failed);
        });
});

gulp.task('test', gulp.series('build', 'start-dev-server', 'build-nextjs-app', 'run-tests'));
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    cssnano = require('gulp-cssnano'),
    kss = require('kss'),
    sassLint = require('gulp-sass-lint'),
    autoprefixer = require('gulp-autoprefixer'),
    gitVersion = require('gulp-gitversion'),
    scssMerge = require('./lib/gulp-scss-merge.js'),
    uglify = require('gulp-uglify'),
    del = require('del'),
    runSequence = require('run-sequence'),
    connect = require('gulp-connect'),
    svg2png = require('gulp-svg2png'),
    webpack = require('webpack-stream'),
    zip = require('gulp-zip'),
    imagemin = require('gulp-imagemin'),
    handlebars = require('gulp-compile-handlebars')
    ;

var paths = {
    assets: './assets/**/*.*',
    assetsDir: './assets',
    scssDir: './assets/sass/**/*.scss',
    scssTemplatesDir: './assets/sass/components/templates',
    kssScssDir: './kss-builder/kss-assets/*.scss',
    kssCssDir: './kss-builder/kss-assets',
    examples: './examples/*.hbs',
    examplePartialsDir: './examples/partials',
    kssBuilderDir: './kss-builder/**/*.*',
    images: './assets/img/**/*.+(png|svg|jpg)',
    scss: './assets/sass/ui-kit.scss',
    js: './assets/js/ui-kit.js',
    markdown: './*.md',
    readme: './README.md',
    outputAssets: './build/latest',
    outputCSS: './build/latest/*.css',
    outputHTML: './build'
};

var options = {
    autoprefixer: {
        browsers: ['last 2 versions', 'ie 7-10', 'iOS >= 4']
    },
    sass: {
        functions: {
            'image-url($img)': function(img) {
              var sass = require('node-sass');
              var String = sass.types.String;
              return new String('/latest/img/' + img.getValue());
            }
        },
        includePaths: [
          './node_modules'
        ]
    },
    webpack: {
        output: {
            filename: 'ui-kit.js',
        }
    },
    handlebars: {
      batch: [ paths.scssTemplatesDir, paths.examplePartialsDir ]
    }
};

gulp.task('lint', function () {
    return gulp.src([paths.scssDir, paths.kssScssDir, '!./assets/sass/vendor/**/*.scss'])
        .pipe(sassLint({
            configFile: '.sass-lint.yml'
        }))
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError());
});

gulp.task('ui-kit', function () {
    gulp.start(['ui-kit.scss', 'ui-kit.js']);
});

gulp.task('ui-kit.scss', function () {
  return gulp.src(paths.scssDir)
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(autoprefixer(options.autoprefixer))
    .pipe(gitVersion())
    .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.js', function () {
    return gulp.src(paths.js)
        .pipe(webpack(options.webpack))
        .pipe(gitVersion())
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.scssmerge', function () {
    return gulp.src(paths.scss)
        .pipe(scssMerge('_ui-kit.scss'))
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.min', function () {
    gulp.start(['ui-kit.min.scss', 'ui-kit.min.js']);
});

gulp.task('ui-kit.min.scss', ['ui-kit.scss'], function () {
    return gulp.src([paths.outputCSS, '!./**/*.min.css'])
        .pipe(cssnano())
        .pipe(gitVersion())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.min.js', function () {
    return gulp.src(paths.js)
        .pipe(webpack({
            output: {
                filename: 'ui-kit.min.js',
            }
        }))
        .pipe(uglify())
        .pipe(gitVersion())
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.img', ['svg2png'], function () {
    return gulp.src(paths.images)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.outputAssets + '/img/'));
});

gulp.task('ui-kit.img.zip', ['ui-kit.img'], function () {
    return gulp.src(paths.outputAssets + '/img/**/*')
        .pipe(zip('images.zip'))
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('svg2png', function () {
    return gulp.src(paths.assetsDir + '/img/icons/*.svg')
        .pipe(svg2png())
        .pipe(gulp.dest(paths.outputAssets + '/img/icons/'));
});

gulp.task('examples', function () {

    return gulp.src(paths.examples)
      .pipe(handlebars({}, options.handlebars))
      .pipe(rename({
        extname: '.html'
      }))
      .pipe(gulp.dest(paths.outputHTML + '/examples')).pipe(connect.reload());
});

gulp.task('markdown', function () {
    return gulp.src(paths.markdown)
        .pipe(gulp.dest(paths.outputHTML));
});

gulp.task('nginx', function () {
    return gulp.src('nginx.conf')
        .pipe(gulp.dest(paths.outputHTML));
});

gulp.task('htmlvalidate', ['examples', 'styleguide'], function (cb) {
    try {
        var validator = require('gulp-html');
        return gulp.src(['build/*.html', 'build/**/*.html'])
            .pipe(validator({'verbose': true}));
    } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
            console.log('WARNING: optional HTML validator not installed, to resolve run:');
            console.log('> npm install AusDTO/gulp-html');
            return cb;
        }
        else {
            throw err;
        }
    }
});

gulp.task('styleguide', ['styleguide.scss'], function () {
    var kssresult = kss({
        source: 'assets/sass',
        destination: paths.outputHTML,
        homepage: '../../README.md',
        builder: 'kss-builder'
    });
    kssresult.then(function () {
        gulp.src('./build/*.html').pipe(connect.reload());
    });

});

gulp.task('styleguide.data', function () {
  var fs = require('fs');
  var source = 'assets/sass';
  var outputFile = 'data-sections.json';
  var customFields = ['tags'];
  var output = [];
  var data, section, i, j;

  // From: http://kss-node.github.io/kss-node/api/master/module-kss.html
  // - The traverse() function reads all the source directories and calls parse()
  // - The parse() function finds the KSS comments in the provided text, creates a
  //   JSON object containing all the parsed data and passes it the new KssStyleGuide(data)
  //   constructor to create a style guide object.
  kss.traverse(source, {'custom': customFields}).then(function(styleData) {
    data = JSON.parse(JSON.stringify(styleData.data.sections));

    for ( i = 0; i < data.length; i++ ) {
      section = data[i];

      if (section.depth === 1) {
        console.log('section', section.referenceNumber, section.header);
        for (j =i+1 ; j < data.length; j++ ) {
          if (data[j].referenceNumber.startsWith(section.referenceNumber + '.')) {
            console.log('child section', data[j].referenceNumber, data[j].header);
            if (section.children) {
              section.children.push(data[j]);
            }
            else {
              section.children = [data[j]];
            }
          }
        }
        output.push(section);
      }
    }

    fs.writeFile(outputFile, JSON.stringify(output), (err) => {
      if (err) throw err;
      console.log(outputFile, 'saved successfully')
    });
  });
});

gulp.task('styleguide.scss', function () {
    return gulp.src(paths.kssScssDir)
        .pipe(sass(options.sass).on('error', sass.logError))
        .pipe(autoprefixer(options.autoprefixer))
        .pipe(gitVersion())
        .pipe(gulp.dest(paths.kssCssDir));
});

gulp.task('clean', function (done) {
    return del([paths.outputAssets, paths.outputHTML], done);
});

gulp.task('default', ['build']);

gulp.task('build', ['lint', 'ui-kit', 'markdown', 'examples', 'styleguide']);

gulp.task('build.prod', function (callback) {
    runSequence('clean',
        ['lint', 'nginx', 'ui-kit', 'ui-kit.min', 'ui-kit.img.zip', 'ui-kit.scssmerge', 'markdown', 'htmlvalidate'],
        callback);
});

gulp.task('watch', ['watch.build']);

gulp.task('watch.build', function () {
    gulp.watch([
            paths.assets,
            paths.examples,
            paths.readme,
            paths.kssBuilderDir,
            '!./kss-builder/kss-assets/kss.css'
        ],
        {verbose: true},
        ['build']);
});

gulp.task('serve', ['webserver', 'build', 'watch.build', 'livereload']);

gulp.task('livereload', function () {
    gulp.watch(['./build/latest/'], () => {
        gulp.src('./build/latest/**/*').pipe(connect.reload());
    });
});

gulp.task('webserver', function () {
    connect.server({
        livereload: true,
        root: 'build'
    });
});
<commit_msg>Adds the 'Collection' custom field to KSS comments<commit_after>'use strict';

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    cssnano = require('gulp-cssnano'),
    kss = require('kss'),
    sassLint = require('gulp-sass-lint'),
    autoprefixer = require('gulp-autoprefixer'),
    gitVersion = require('gulp-gitversion'),
    scssMerge = require('./lib/gulp-scss-merge.js'),
    uglify = require('gulp-uglify'),
    del = require('del'),
    runSequence = require('run-sequence'),
    connect = require('gulp-connect'),
    svg2png = require('gulp-svg2png'),
    webpack = require('webpack-stream'),
    zip = require('gulp-zip'),
    imagemin = require('gulp-imagemin'),
    handlebars = require('gulp-compile-handlebars')
    ;

var paths = {
    assets: './assets/**/*.*',
    assetsDir: './assets',
    scssDir: './assets/sass/**/*.scss',
    scssTemplatesDir: './assets/sass/components/templates',
    kssScssDir: './kss-builder/kss-assets/*.scss',
    kssCssDir: './kss-builder/kss-assets',
    examples: './examples/*.hbs',
    examplePartialsDir: './examples/partials',
    kssBuilderDir: './kss-builder/**/*.*',
    images: './assets/img/**/*.+(png|svg|jpg)',
    scss: './assets/sass/ui-kit.scss',
    js: './assets/js/ui-kit.js',
    markdown: './*.md',
    readme: './README.md',
    outputAssets: './build/latest',
    outputCSS: './build/latest/*.css',
    outputHTML: './build'
};

var options = {
    autoprefixer: {
        browsers: ['last 2 versions', 'ie 7-10', 'iOS >= 4']
    },
    sass: {
        functions: {
            'image-url($img)': function(img) {
              var sass = require('node-sass');
              var String = sass.types.String;
              return new String('/latest/img/' + img.getValue());
            }
        },
        includePaths: [
          './node_modules'
        ]
    },
    webpack: {
        output: {
            filename: 'ui-kit.js',
        }
    },
    handlebars: {
      batch: [ paths.scssTemplatesDir, paths.examplePartialsDir ]
    }
};

gulp.task('lint', function () {
    return gulp.src([paths.scssDir, paths.kssScssDir, '!./assets/sass/vendor/**/*.scss'])
        .pipe(sassLint({
            configFile: '.sass-lint.yml'
        }))
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError());
});

gulp.task('ui-kit', function () {
    gulp.start(['ui-kit.scss', 'ui-kit.js']);
});

gulp.task('ui-kit.scss', function () {
  return gulp.src(paths.scssDir)
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(autoprefixer(options.autoprefixer))
    .pipe(gitVersion())
    .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.js', function () {
    return gulp.src(paths.js)
        .pipe(webpack(options.webpack))
        .pipe(gitVersion())
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.scssmerge', function () {
    return gulp.src(paths.scss)
        .pipe(scssMerge('_ui-kit.scss'))
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.min', function () {
    gulp.start(['ui-kit.min.scss', 'ui-kit.min.js']);
});

gulp.task('ui-kit.min.scss', ['ui-kit.scss'], function () {
    return gulp.src([paths.outputCSS, '!./**/*.min.css'])
        .pipe(cssnano())
        .pipe(gitVersion())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.min.js', function () {
    return gulp.src(paths.js)
        .pipe(webpack({
            output: {
                filename: 'ui-kit.min.js',
            }
        }))
        .pipe(uglify())
        .pipe(gitVersion())
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('ui-kit.img', ['svg2png'], function () {
    return gulp.src(paths.images)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.outputAssets + '/img/'));
});

gulp.task('ui-kit.img.zip', ['ui-kit.img'], function () {
    return gulp.src(paths.outputAssets + '/img/**/*')
        .pipe(zip('images.zip'))
        .pipe(gulp.dest(paths.outputAssets));
});

gulp.task('svg2png', function () {
    return gulp.src(paths.assetsDir + '/img/icons/*.svg')
        .pipe(svg2png())
        .pipe(gulp.dest(paths.outputAssets + '/img/icons/'));
});

gulp.task('examples', function () {

    return gulp.src(paths.examples)
      .pipe(handlebars({}, options.handlebars))
      .pipe(rename({
        extname: '.html'
      }))
      .pipe(gulp.dest(paths.outputHTML + '/examples')).pipe(connect.reload());
});

gulp.task('markdown', function () {
    return gulp.src(paths.markdown)
        .pipe(gulp.dest(paths.outputHTML));
});

gulp.task('nginx', function () {
    return gulp.src('nginx.conf')
        .pipe(gulp.dest(paths.outputHTML));
});

gulp.task('htmlvalidate', ['examples', 'styleguide'], function (cb) {
    try {
        var validator = require('gulp-html');
        return gulp.src(['build/*.html', 'build/**/*.html'])
            .pipe(validator({'verbose': true}));
    } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
            console.log('WARNING: optional HTML validator not installed, to resolve run:');
            console.log('> npm install AusDTO/gulp-html');
            return cb;
        }
        else {
            throw err;
        }
    }
});

gulp.task('styleguide', ['styleguide.scss'], function () {
    var kssresult = kss({
        source: 'assets/sass',
        destination: paths.outputHTML,
        homepage: '../../README.md',
        builder: 'kss-builder'
    });
    kssresult.then(function () {
        gulp.src('./build/*.html').pipe(connect.reload());
    });

});

gulp.task('styleguide.data', function () {
  var fs = require('fs');
  var source = 'assets/sass';
  var outputFile = 'data-sections.json';
  var customFields = ['tags', 'collection'];
  var output = [];
  var data, section, i, j;

  // From: http://kss-node.github.io/kss-node/api/master/module-kss.html
  // - The traverse() function reads all the source directories and calls parse()
  // - The parse() function finds the KSS comments in the provided text, creates a
  //   JSON object containing all the parsed data and passes it the new KssStyleGuide(data)
  //   constructor to create a style guide object.
  kss.traverse(source, {'custom': customFields}).then(function(styleData) {
    data = JSON.parse(JSON.stringify(styleData.data.sections));

    for ( i = 0; i < data.length; i++ ) {
      section = data[i];

      if (section.depth === 1) {
        console.log('section', section.referenceNumber, section.header);
        for (j =i+1 ; j < data.length; j++ ) {
          if (data[j].referenceNumber.startsWith(section.referenceNumber + '.')) {
            console.log('child section', data[j].referenceNumber, data[j].header);
            if (section.children) {
              section.children.push(data[j]);
            }
            else {
              section.children = [data[j]];
            }
          }
        }
        output.push(section);
      }
    }

    fs.writeFile(outputFile, JSON.stringify(output), (err) => {
      if (err) throw err;
      console.log(outputFile, 'saved successfully')
    });
  });
});

gulp.task('styleguide.scss', function () {
    return gulp.src(paths.kssScssDir)
        .pipe(sass(options.sass).on('error', sass.logError))
        .pipe(autoprefixer(options.autoprefixer))
        .pipe(gitVersion())
        .pipe(gulp.dest(paths.kssCssDir));
});

gulp.task('clean', function (done) {
    return del([paths.outputAssets, paths.outputHTML], done);
});

gulp.task('default', ['build']);

gulp.task('build', ['lint', 'ui-kit', 'markdown', 'examples', 'styleguide']);

gulp.task('build.prod', function (callback) {
    runSequence('clean',
        ['lint', 'nginx', 'ui-kit', 'ui-kit.min', 'ui-kit.img.zip', 'ui-kit.scssmerge', 'markdown', 'htmlvalidate'],
        callback);
});

gulp.task('watch', ['watch.build']);

gulp.task('watch.build', function () {
    gulp.watch([
            paths.assets,
            paths.examples,
            paths.readme,
            paths.kssBuilderDir,
            '!./kss-builder/kss-assets/kss.css'
        ],
        {verbose: true},
        ['build']);
});

gulp.task('serve', ['webserver', 'build', 'watch.build', 'livereload']);

gulp.task('livereload', function () {
    gulp.watch(['./build/latest/'], () => {
        gulp.src('./build/latest/**/*').pipe(connect.reload());
    });
});

gulp.task('webserver', function () {
    connect.server({
        livereload: true,
        root: 'build'
    });
});
<|endoftext|>


<commit_before>var gulp    = require("gulp");
var notify  = require("gulp-notify");
var run     = require("gulp-run");
var phpunit = require("gulp-phpunit");

gulp.task("tests", function ()
{
    gulp.src("./tests/TestBase.php")
		    .pipe( run("clear") )
		        .pipe( phpunit("phpunit", {
		            debug: false,
		            notify: true
		        }))
		    .on("error", function() {
		        run("notify-send 'Tests Failed' 'Got some problems dude.'").exec();
		    })
        	.pipe( run("notify-send 'Tests Passed' 'Nailed it.'"));
});

gulp.task("watch", function()
{
    gulp.watch([ "./src/**/*.php", "./tests/**/*"], [ "tests" ]);
})

gulp.task("default", [ "tests", "watch" ]);
<commit_msg>Get rid of dude :)<commit_after>var gulp    = require("gulp");
var notify  = require("gulp-notify");
var run     = require("gulp-run");
var phpunit = require("gulp-phpunit");

gulp.task("tests", function ()
{
    gulp.src("./tests/TestBase.php")
		    .pipe( run("clear") )
		        .pipe( phpunit("phpunit", {
		            debug: false,
		            notify: true
		        }))
		    .on("error", function() {
		        run("notify-send 'Tests Failed' 'Got some problems buddy.'").exec();
		    })
        	.pipe( run("notify-send 'Tests Passed' 'Nailed it.'"));
});

gulp.task("watch", function()
{
    gulp.watch([ "./src/**/*.php", "./tests/**/*"], [ "tests" ]);
})

gulp.task("default", [ "tests", "watch" ]);
<|endoftext|>


<commit_before>var VisualANN = {};

VisualANN.activation = (function () {
    'use strict';
    var sigmoid = function (inputSum) {
	return 1 / (1 + Math.exp(- inputSum));
    };
    return {
	SIGMOID: sigmoid
    };
}());

VisualANN.core = (function () {
    'use strict';
    var
    /**
     * @private
     * @param {Network} network The network to generate
     * a new, activated, network from.
     * @param {Array} inputs An array of { neuron: \<Network\>,
     * value: \<number\> }-objects. Typically one such object per
     * input neuron.
     * @returns {Network} A network with updated neuron activations.
     */
    activate = function (network, inputs) {
	var sumInput = function (neuron) {
		var input = inputs.find(function (input) {
		    return input.neuron === neuron;
		});
		// If neuron is among input neurons return its value.
		if (input) {
		    return input.value;
		}
		// ... otherwise, collect inputs form other neurons
		return network.getSynapses().map(function (syn) {
		    if (syn.getToNeuron() === neuron) {
			return syn.getFromNeuron()
			    .getCurrentActivation() *
			    syn.getStrength();
		    } else {
			return 0;
		    }
		}).reduce(function (sum, val) { // ... and sum them.
		    return sum + val;
		}, 0);
	},
	    newNeurons = network.getNeurons().map(
		function (neuron) {
		    return neuron.activate(sumInput(neuron));
		}),
	    newSynapses = network.getSynapses().map(
		function (synapse) {
		    return new Synapse(
			newNeurons.find(function (neuron) {
			    return neuron.getSource() ===
				synapse.getFromNeuron();
			}),
			newNeurons.find(function (neuron) {
			    return neuron.getSource() ===
				synapse.getToNeuron();
			}),
			synapse.getStrength());
		});
	return new Network(newNeurons, newSynapses);
    },
    /**
     * Creates a new Network with an additional neuron added to it.
     * @private
     * @param {Network} network A network to add a new neuron to.
     * @param {Neuron} neuron - The new neuron to add.
     * @returns {Network}
     */
    addNeuron = function (network, neuron) {
	return new Network(network.getNeurons().concat(neuron),
			   network.getSynapses());
    },
    /**
     * Creates a new Network with an additional synapse added to it.
     * @private
     * @param {Network} network A network to add a new synapse to.
     * @param {Synapse} synapse - A synapse to add.
     * @returns {Network}
     */
    addSynapse = function (network, synapse) {
	return new Network(network.getNeurons(),
			   network.getSynapses().concat(synapse));
    },
    /**
     * A constructor for Network objects.
     * @param {Array<Neuron>} [neurons=[]] Initial neurons.
     * @param {Array<Synapse>} [synapses=[]] Initial synapses.
     * @returns {Network}
     */
    Network = function (neurons, synapses) {
	var neus = neurons || [],
	    syns = synapses || [];
	/**
	 * Creates a new Network by activating all neurons in the
	 * network based on current neuron activations.
	 * @name Network.activate
	 * @param {Array<Object>} inputs An Array of Objects on the
	 * form { neuron: \<Neuron\>, value: \<number\> }.
	 * @returns {Network}
	 */
	this.activate = function (inputs) {
	    return activate(this, inputs);
	};
	/**
	 * Creates a new Network with a new neuron added to it.
	 * @name Network.addNeuron
	 * @param {Neuron} neuron The neuron to add.
	 * @returns {Network}
	 */
	this.addNeuron = function (neuron) {
	    return addNeuron(this, neuron);
	};
	/**
	 * Creates a new Network with a new synapse added to it.
	 * @name Network.addSynapse
	 * @param {Synapse} synapse The synapse to add.
	 * @returns {Network}
	 */
	this.addSynapse = function (synapse) {
	    return addSynapse(this, synapse);
	};
	/**
	 * Retrieve a specific neuron from the network.
	 * @name Network.getNeuron
	 * @param {number} i The index of the neuron to retrieve.
	 * @returns {Neuron}
	 */
	this.getNeuron = function (i) {
	    return neus[i];
	};
	/**
	 * Retrieve all neurons from the network.
	 * @name Network.getNeurons
	 * @returns {Array<Neuron>}
	 */
	this.getNeurons = function () {
	    return neus;
	};
	/**
	 * Retrieve a specific synapse from the network.
	 * @name Network.getSynapse
	 * @param {number} i The index of the synapse to retrieve.
	 * @returns {Synapse}
	 */
	this.getSynapse = function (i) {
	    return syns[i];
	};
	/**
	 * Retrieve all synapses from the network.
	 * @name Network.getSynapses
	 * @returns {Array<Synapse>}
	 */
	this.getSynapses = function () {
	    return syns;
	};
    },
    /**
     * A constructor for Neuron objects.
     * @param {Function} activationFunction An activation function
     * taking the sum of neuron inputs as its single argument.
     * @param {string} [name=''] A name to use for display purposes.
     * @param {number} [activation=0] The initial activation.
     * @param {Neuron} [source=undefined] A reference to a previous
     * neuron, if this neuron has replaced one.
     * @returns {Neuron}
     */
    Neuron = function (activationFunction, name, activation, source) {
	/**
	 * Create a new neuron by activating this one given the sum of
	 * inputs.
	 * @name Neuron.activate
	 * @param {number} inputSum The sum of inputs.
	 * @returns {Neuron}
	 */
	this.activate = function (inputSum) {
	    return new Neuron(activationFunction,
			      name,
			      activationFunction(inputSum),
			      this);
	};
	/**
	 * Get the current activation.
	 * @name Neuron.getCurrentActivation
	 * @returns {number}
	 */
	this.getCurrentActivation = function () {
	    return activation || 0;
	};
	/**
	 * Get a displayable name.
	 * @name Neuron.getName
	 * @returns {string}
	 */
	this.getName = function () { return name || ''; };
	/**
	 * Get the neuron that this neuron has replaced.
	 * @name Neuron.getSource
	 * @returns {Neuron}
	 */
	this.getSource =  function () { return source; };
    },
    requirements = document.createElement('script'),
    /**
     * A constructor for Synapse objects.
     * @param {Neuron} fromNeuron
     * @param {Neuron} toNeuron
     * @param {number} strength
     * @returns {Synapse}
     */
    Synapse = function (fromNeuron, toNeuron, strength) {
	/**
	 * @name Synapse.getFromNeuron
	 * @returns {Neuron}
	 */
	this.getFromNeuron = function () { return fromNeuron; };
	/**
	 * @name Synapse.getToNeuron
	 * @returns {Neuron}
	 */
	this.getToNeuron = function () { return toNeuron; };
	/**
	 * @name Synapse.getStrength
	 * @returns {number}
	 */
	this.getStrength = function () { return strength; };
    };
    // Things to require.
    requirements.setAttribute('src', 'js-visual-ann/visual-ann-view.js');
    document.head.append(requirements);
    // Things to export.
    return {
	Network: Network,
	Neuron: Neuron,
	Synapse: Synapse
    };
}());
<commit_msg>De-coupling view from core.<commit_after>var VisualANN = {};

VisualANN.activation = (function () {
    'use strict';
    var sigmoid = function (inputSum) {
	return 1 / (1 + Math.exp(- inputSum));
    };
    return {
	SIGMOID: sigmoid
    };
}());

VisualANN.core = (function () {
    'use strict';
    var
    /**
     * @private
     * @param {Network} network The network to generate
     * a new, activated, network from.
     * @param {Array} inputs An array of { neuron: \<Network\>,
     * value: \<number\> }-objects. Typically one such object per
     * input neuron.
     * @returns {Network} A network with updated neuron activations.
     */
    activate = function (network, inputs) {
	var sumInput = function (neuron) {
		var input = inputs.find(function (input) {
		    return input.neuron === neuron;
		});
		// If neuron is among input neurons return its value.
		if (input) {
		    return input.value;
		}
		// ... otherwise, collect inputs form other neurons
		return network.getSynapses().map(function (syn) {
		    if (syn.getToNeuron() === neuron) {
			return syn.getFromNeuron()
			    .getCurrentActivation() *
			    syn.getStrength();
		    } else {
			return 0;
		    }
		}).reduce(function (sum, val) { // ... and sum them.
		    return sum + val;
		}, 0);
	},
	    newNeurons = network.getNeurons().map(
		function (neuron) {
		    return neuron.activate(sumInput(neuron));
		}),
	    newSynapses = network.getSynapses().map(
		function (synapse) {
		    return new Synapse(
			newNeurons.find(function (neuron) {
			    return neuron.getSource() ===
				synapse.getFromNeuron();
			}),
			newNeurons.find(function (neuron) {
			    return neuron.getSource() ===
				synapse.getToNeuron();
			}),
			synapse.getStrength());
		});
	return new Network(newNeurons, newSynapses);
    },
    /**
     * Creates a new Network with an additional neuron added to it.
     * @private
     * @param {Network} network A network to add a new neuron to.
     * @param {Neuron} neuron - The new neuron to add.
     * @returns {Network}
     */
    addNeuron = function (network, neuron) {
	return new Network(network.getNeurons().concat(neuron),
			   network.getSynapses());
    },
    /**
     * Creates a new Network with an additional synapse added to it.
     * @private
     * @param {Network} network A network to add a new synapse to.
     * @param {Synapse} synapse - A synapse to add.
     * @returns {Network}
     */
    addSynapse = function (network, synapse) {
	return new Network(network.getNeurons(),
			   network.getSynapses().concat(synapse));
    },
    /**
     * A constructor for Network objects.
     * @param {Array<Neuron>} [neurons=[]] Initial neurons.
     * @param {Array<Synapse>} [synapses=[]] Initial synapses.
     * @returns {Network}
     */
    Network = function (neurons, synapses) {
	var neus = neurons || [],
	    syns = synapses || [];
	/**
	 * Creates a new Network by activating all neurons in the
	 * network based on current neuron activations.
	 * @name Network.activate
	 * @param {Array<Object>} inputs An Array of Objects on the
	 * form { neuron: \<Neuron\>, value: \<number\> }.
	 * @returns {Network}
	 */
	this.activate = function (inputs) {
	    return activate(this, inputs);
	};
	/**
	 * Creates a new Network with a new neuron added to it.
	 * @name Network.addNeuron
	 * @param {Neuron} neuron The neuron to add.
	 * @returns {Network}
	 */
	this.addNeuron = function (neuron) {
	    return addNeuron(this, neuron);
	};
	/**
	 * Creates a new Network with a new synapse added to it.
	 * @name Network.addSynapse
	 * @param {Synapse} synapse The synapse to add.
	 * @returns {Network}
	 */
	this.addSynapse = function (synapse) {
	    return addSynapse(this, synapse);
	};
	/**
	 * Retrieve a specific neuron from the network.
	 * @name Network.getNeuron
	 * @param {number} i The index of the neuron to retrieve.
	 * @returns {Neuron}
	 */
	this.getNeuron = function (i) {
	    return neus[i];
	};
	/**
	 * Retrieve all neurons from the network.
	 * @name Network.getNeurons
	 * @returns {Array<Neuron>}
	 */
	this.getNeurons = function () {
	    return neus;
	};
	/**
	 * Retrieve a specific synapse from the network.
	 * @name Network.getSynapse
	 * @param {number} i The index of the synapse to retrieve.
	 * @returns {Synapse}
	 */
	this.getSynapse = function (i) {
	    return syns[i];
	};
	/**
	 * Retrieve all synapses from the network.
	 * @name Network.getSynapses
	 * @returns {Array<Synapse>}
	 */
	this.getSynapses = function () {
	    return syns;
	};
    },
    /**
     * A constructor for Neuron objects.
     * @param {Function} activationFunction An activation function
     * taking the sum of neuron inputs as its single argument.
     * @param {string} [name=''] A name to use for display purposes.
     * @param {number} [activation=0] The initial activation.
     * @param {Neuron} [source=undefined] A reference to a previous
     * neuron, if this neuron has replaced one.
     * @returns {Neuron}
     */
    Neuron = function (activationFunction, name, activation, source) {
	/**
	 * Create a new neuron by activating this one given the sum of
	 * inputs.
	 * @name Neuron.activate
	 * @param {number} inputSum The sum of inputs.
	 * @returns {Neuron}
	 */
	this.activate = function (inputSum) {
	    return new Neuron(activationFunction,
			      name,
			      activationFunction(inputSum),
			      this);
	};
	/**
	 * Get the current activation.
	 * @name Neuron.getCurrentActivation
	 * @returns {number}
	 */
	this.getCurrentActivation = function () {
	    return activation || 0;
	};
	/**
	 * Get a displayable name.
	 * @name Neuron.getName
	 * @returns {string}
	 */
	this.getName = function () { return name || ''; };
	/**
	 * Get the neuron that this neuron has replaced.
	 * @name Neuron.getSource
	 * @returns {Neuron}
	 */
	this.getSource =  function () { return source; };
    },
    /**
     * A constructor for Synapse objects.
     * @param {Neuron} fromNeuron
     * @param {Neuron} toNeuron
     * @param {number} strength
     * @returns {Synapse}
     */
    Synapse = function (fromNeuron, toNeuron, strength) {
	/**
	 * @name Synapse.getFromNeuron
	 * @returns {Neuron}
	 */
	this.getFromNeuron = function () { return fromNeuron; };
	/**
	 * @name Synapse.getToNeuron
	 * @returns {Neuron}
	 */
	this.getToNeuron = function () { return toNeuron; };
	/**
	 * @name Synapse.getStrength
	 * @returns {number}
	 */
	this.getStrength = function () { return strength; };
    };
    // Things to export.
    return {
	Network: Network,
	Neuron: Neuron,
	Synapse: Synapse
    };
}());
<|endoftext|>


<commit_before>;(function() {
  'use strict';

  /*  Dependencies  */
  var lib    = require('./lib')
  var gulp   = require('gulp');
  var $      = require('gulp-load-plugins')({lazy:true});
  var del    = require('del');

  /* Tasks */

var tasks = lib.tasks

// ================= DEFAULT

gulp
  .task('default', $.sequence('dev'));

//================== DEV
gulp
  .task( 'dev',
    $.sequence( 'clean'
              , 'build:dev'
              , 'start:dev'
              ));

// ====== BUILD
gulp
  .task( 'js:dev'    , tasks.js.dev     )
  .task( 'css:dev'   , tasks.css.dev    )
  .task( 'styl:dev'  , tasks.styl.dev   )
  .task( 'html:dev'  , tasks.html.dev   )
  .task( 'jade:dev'  , tasks.jade.dev   )
  .task( 'images:dev', tasks.images.dev )
  .task( 'build:dev' ,
    $.sequence( 'js:dev'
              , 'css:dev'
              , 'styl:dev'
              , 'html:dev'
              , 'jade:dev'
              , 'images:dev'
              ));

// ====== START
gulp
  .task( 'vendor:dev' , tasks.vendor.dev )
  .task( 'inject:dev' , tasks.inject.dev )
  .task( 'server:dev' , tasks.server.dev )
  .task( 'watch:dev'  , tasks.watch.dev  )
  .task( 'start:dev'  ,
    $.sequence(
                'vendor:dev'
              , 'inject:dev'
              , 'server:dev'
              , 'watch:dev'
              ));

// //================== STAGE

gulp
  .task('stage',
    $.sequence('clean',
               'build:stage',
               'start:stage'));

// ====== BUILD

gulp
  .task('js:stage', tasks.js.stage)
  .task('css:stage', tasks.css.stage)
  .task('styl:stage', tasks.styl.stage)
  .task('html:stage', tasks.html.stage)
  .task('jade:stage', tasks.jade.stage)
  .task('images:stage', tasks.images.stage)
  .task('build:stage',
    $.sequence('js:stage',
               'css:stage',
               'styl:stage',
               'html:stage',
               'jade:stage',
               'images:stage'));

// ====== START

gulp
  .task('vendor:stage', tasks.vendor.stage)
  .task('inject:stage', tasks.inject.stage)
  .task('server:stage', tasks.server.stage)
  .task('watch:stage', tasks.watch.stage)
  .task('start:stage',
    $.sequence(
      'vendor:stage',
      'inject:stage',
      'server:stage',
      'watch:stage'
    ));

//================== PROD

gulp
  .task('prod',
    $.sequence(
      'clean',
      'build:stage',
      'vendor:stage',
      'inject:stage'
    )
  );

//================== DEPLOY

gulp
  .task('deploy', function() {
    if (process.env.NODE_ENV === 'production') gulp.start('prod');
  });

//================== CLEAN
gulp
  .task('clean', del.bind(null, ['build']));

/******************************************************************************
 * GitHub commands
 *****************************************************************************/

gulp
  .task('git:rebase', tasks.git.rebase)
  .task('git:push', tasks.git.push)
  .task('git:pr', $.sequence('lint', 'git:rebase', 'git:push'));

/******************************************************************************
 * Testing suite
 *****************************************************************************/

gulp
  .task('lint', tasks.lint)
  .task('karma', tasks.karma)
  .task('nightwatch', tasks.nightwatch)
  .task('mocha', tasks.mocha)
  .task('test',
    $.sequence('lint',
               'karma',
               'mocha')
  );

/**
 * coveralls
 * =========
 * Sends code coverage data to Coveralls.
 */
gulp.task('coveralls', tasks.coveralls);

})();
<commit_msg>update gulpfile to build html/jade templates on test<commit_after>;(function() {
  'use strict';

  /*  Dependencies  */
  var lib    = require('./lib')
  var gulp   = require('gulp');
  var $      = require('gulp-load-plugins')({lazy:true});
  var del    = require('del');

  /* Tasks */

var tasks = lib.tasks

// ================= DEFAULT

gulp
  .task('default', $.sequence('dev'));

//================== DEV
gulp
  .task( 'dev',
    $.sequence( 'clean'
              , 'build:dev'
              , 'start:dev'
              ));

// ====== BUILD
gulp
  .task( 'js:dev'    , tasks.js.dev     )
  .task( 'css:dev'   , tasks.css.dev    )
  .task( 'styl:dev'  , tasks.styl.dev   )
  .task( 'html:dev'  , tasks.html.dev   )
  .task( 'jade:dev'  , tasks.jade.dev   )
  .task( 'images:dev', tasks.images.dev )
  .task( 'build:dev' ,
    $.sequence( 'js:dev'
              , 'css:dev'
              , 'styl:dev'
              , 'html:dev'
              , 'jade:dev'
              , 'images:dev'
              ));

// ====== START
gulp
  .task( 'vendor:dev' , tasks.vendor.dev )
  .task( 'inject:dev' , tasks.inject.dev )
  .task( 'server:dev' , tasks.server.dev )
  .task( 'watch:dev'  , tasks.watch.dev  )
  .task( 'start:dev'  ,
    $.sequence(
                'vendor:dev'
              , 'inject:dev'
              , 'server:dev'
              , 'watch:dev'
              ));

// //================== STAGE

gulp
  .task('stage',
    $.sequence('clean',
               'build:stage',
               'start:stage'));

// ====== BUILD

gulp
  .task('js:stage', tasks.js.stage)
  .task('css:stage', tasks.css.stage)
  .task('styl:stage', tasks.styl.stage)
  .task('html:stage', tasks.html.stage)
  .task('jade:stage', tasks.jade.stage)
  .task('images:stage', tasks.images.stage)
  .task('build:stage',
    $.sequence('js:stage',
               'css:stage',
               'styl:stage',
               'html:stage',
               'jade:stage',
               'images:stage'));

// ====== START

gulp
  .task('vendor:stage', tasks.vendor.stage)
  .task('inject:stage', tasks.inject.stage)
  .task('server:stage', tasks.server.stage)
  .task('watch:stage', tasks.watch.stage)
  .task('start:stage',
    $.sequence(
      'vendor:stage',
      'inject:stage',
      'server:stage',
      'watch:stage'
    ));

//================== PROD

gulp
  .task('prod',
    $.sequence(
      'clean',
      'build:stage',
      'vendor:stage',
      'inject:stage'
    )
  );

//================== DEPLOY

gulp
  .task('deploy', function() {
    if (process.env.NODE_ENV === 'production') gulp.start('prod');
  });

//================== CLEAN
gulp
  .task('clean', del.bind(null, ['build']));

/******************************************************************************
 * GitHub commands
 *****************************************************************************/

gulp
  .task('git:rebase', tasks.git.rebase)
  .task('git:push', tasks.git.push)
  .task('git:pr', $.sequence('lint', 'git:rebase', 'git:push'));

/******************************************************************************
 * Testing suite
 *****************************************************************************/

gulp
  .task('lint', tasks.lint)
  .task('karma', tasks.karma)
  .task('nightwatch', tasks.nightwatch)
  .task('mocha', tasks.mocha)
  .task('test',
    $.sequence('clean',
               'lint',
               // Build Jade templates for Karma tests
               'jade:dev',
               // Build HTML templates for Karma tests
               'html:dev',
               'karma',
               'mocha')
  );

/**
 * coveralls
 * =========
 * Sends code coverage data to Coveralls.
 */
gulp.task('coveralls', tasks.coveralls);

})();
<|endoftext|>