<commit_before>function FASymbol(name, id, unicode, $icon) {
    this.name = name;
    this.id = id;
    this.unicode = unicode;
    this.$icon = $icon;
}

$(window).on('load', function () {

    var symbol = "\uf004";
    var canvas = document.getElementById('canvas');
    var sideLength = 1024;
    canvas.width = sideLength;
    canvas.height = sideLength;
    var ctx = canvas.getContext('2d');
    draw();

    $("#size").on("input", draw);

    $("#color").spectrum({
        color: "#ffffff",
        showButtons: false,
        showAlpha: true,
        //change: updateBorders,
        move: function(color) {
            var rgba = colorToRgba(color);
            $(this).css("background-color", rgba);
            $("#color_text").val(rgba);
            draw();
        }
    });

    $("#background_color").spectrum({
        color: "#f85032",
        showButtons: false,
        showAlpha: true,
        //change: updateBorders,
        move: function(color) {
            var rgba = colorToRgba(color);
            $(this).css("background-color", rgba);
            $("#background_color_text").val(rgba);
            draw();
        }
    });

    function colorToRgba(color) {
        return "rgba("
            + color.toRgb().r  + ", "
            + color.toRgb().g  + ", "
            + color.toRgb().b  + ", "
            + color.toRgb().a  + ")";
    }

    var symbols = [];
    $("#search").on("input", function () {
        var phrase = $("#search").val().toLowerCase();
        for (var i = 0; i < symbols.length; i++) {
            if (symbols[i].id.indexOf(phrase) !== -1) {
                symbols[i].$icon.parent().show();
            } else {
                symbols[i].$icon.parent().hide();
            }
        }
    });

    $("#download").on("click", function () {
        canvas.toBlob(function (blob) {
            saveAs(blob, "favicon.png");
        });
    });

    var $right = $('#right');
    $.each(icons, function (index, icon) {
        var $iconOuter = $("
").addClass("icon_outer");
        var $icon = $("
").addClass("icon").append($(''));
        $icon.append($("
").addClass("icon_text").text(icon.id));
        $iconOuter.append($icon);
        $right.append($iconOuter);

        symbols.push(new FASymbol(icon.name, icon.id, icon.unicode, $icon));
    });

    $(".icon").on("click", function () {
        symbol = window.getComputedStyle($(this).children().get()[0], ':before').content.substring(1, 2);
        draw();
    });

    function draw() {
        if (sideLength > 0) {
            var color = $("#color_text").val();
            var backgroundColor = $("#background_color_text").val();
            var i = sideLength;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = backgroundColor;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            do {
                ctx.font = i + "px FontAwesome";
                i--;
            } while (ctx.measureText(symbol).width > sideLength);
            ctx.font = (i * ($("#size").val() / 100)) + "px FontAwesome";

            ctx.fillStyle = "rgba(0, 0, 0, 1)";
            ctx.globalCompositeOperation = "destination-out";
            ctx.fillText(symbol, sideLength / 2, sideLength / 2);
            ctx.fillStyle = color;
            ctx.globalCompositeOperation = "source-over";
            ctx.fillText(symbol, sideLength / 2, sideLength / 2);
            canvasToFavicon(canvas);
        }
    }
});

// used to update the icons
//function updateIcons() {
//    $.get('https://rawgit.com/FortAwesome/Font-Awesome/master/src/icons.yml', function (data) {
//        var parsedYaml = jsyaml.load(data);
//        console.log(JSON.stringify(parsedYaml));
//    });
//
//}<commit_msg>Change color input to be applied to picker, closes #1<commit_after>function FASymbol(name, id, unicode, $icon) {
    this.name = name;
    this.id = id;
    this.unicode = unicode;
    this.$icon = $icon;
}

$(window).on('load', function () {
    var $color = $("#color");
    var $color_text = $("#color_text");
    var $background_color = $("#background_color");
    var $background_color_text = $("#background_color_text");
    var $search = $("#search");
    var $right = $('#right');
    var $size = $("#size");

    var symbol = "\uf004";
    var canvas = document.getElementById('canvas');
    var sideLength = 1024;
    canvas.width = sideLength;
    canvas.height = sideLength;
    var ctx = canvas.getContext('2d');
    var symbols = [];

    $size.on("input", draw);
    $color_text.on("input", updateColor.bind(updateColor, $color, $color_text, false));
    $background_color_text.on("input", updateColor.bind(updateColor, $background_color, $background_color_text, false));

    $color.spectrum({
        color: "#ffffff",
        showButtons: false,
        showAlpha: true,
        move: updateColor.bind(updateColor, $color, $color_text, true)
    });

    $background_color.spectrum({
        color: "#f85032",
        showButtons: false,
        showAlpha: true,
        move: updateColor.bind(updateColor, $background_color, $background_color_text, true)
    });

    $search.on("input", function () {
        var phrase = $search.val().toLowerCase();
        for (var i = 0; i < symbols.length; i++) {
            if (symbols[i].id.indexOf(phrase) !== -1) {
                symbols[i].$icon.parent().show();
            } else {
                symbols[i].$icon.parent().hide();
            }
        }
    });

    $("#download").on("click", function () {
        canvas.toBlob(function (blob) {
            saveAs(blob, "favicon.png");
        });
    });

    $(".icon").on("click", function () {
        symbol = window.getComputedStyle($(this).children().get()[0], ':before').content.substring(1, 2);
        draw();
    });

    $.each(icons, function (index, icon) {
        var $iconOuter = $("
").addClass("icon_outer");
        var $icon = $("
").addClass("icon").append($(''));
        $icon.append($("
").addClass("icon_text").text(icon.id));
        $iconOuter.append($icon);
        $right.append($iconOuter);

        symbols.push(new FASymbol(icon.name, icon.id, icon.unicode, $icon));
    });
    draw();

    function updateColor($color, $color_text, fromPicker) {
        if (!fromPicker) {
            $color.spectrum("set", $color_text.val());
        }
        var rgba = colorToRgba($color.spectrum("get"));
        $color.css("background-color", rgba);
        if (fromPicker) {
            $color_text.val(rgba);
        }
        draw();
    }

    function colorToRgba(color) {
        return "rgba("
            + color.toRgb().r + ", "
            + color.toRgb().g + ", "
            + color.toRgb().b + ", "
            + color.toRgb().a + ")";
    }

    function draw() {
        if (sideLength > 0) {
            var i = sideLength;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = $background_color_text.val();
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            setFontSize();
            ctx.fillStyle = "rgba(0, 0, 0, 1)";
            ctx.globalCompositeOperation = "destination-out";
            ctx.fillText(symbol, sideLength / 2, sideLength / 2);
            ctx.fillStyle = $color_text.val();
            ctx.globalCompositeOperation = "source-over";
            ctx.fillText(symbol, sideLength / 2, sideLength / 2);
            canvasToFavicon(canvas);
        }
    }

    function setFontSize() {
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        do {
            ctx.font = i + "px FontAwesome";
            i--;
        } while (ctx.measureText(symbol).width > sideLength);
        ctx.font = (i * ($size.val() / 100)) + "px FontAwesome";
    }
});

// used to update the icons
//function updateIcons() {
//    $.get('https://rawgit.com/FortAwesome/Font-Awesome/master/src/icons.yml', function (data) {
//        var parsedYaml = jsyaml.load(data);
//        console.log(JSON.stringify(parsedYaml));
//    });
//
//}<|endoftext|>


<commit_before>
var startGame = function(){
  return false;
};

function Ship(shipName, shipSize){
  this.shipName = shipName || "";
  this.shipSize = shipSize || 0;
  // return false;
}

function Submarine(shipName, shipSize, shipType) {
  this.base = Ship;
  this.base(shipName,shipSize);
  this.shipType = "Submarine";
}

Submarine.prototype = new Ship();

var smallSub = new Submarine("Submarine", 3);

var Players = function(){
  return false;
};

var Scoreboard = function(){
  return false;
};

var buildGameBoard = function(boardSize) {
  var gameBoard = [];

  for (var row = 0; row < boardSize; row++) {
    var boardRow = [];
    for (var column = 0; column < boardSize; column++) {
      // We are creating an Object (can create constructor in another location)
      var squareTile = {
        position: [row, column]
      };
      boardRow.push(squareTile);
    }
    gameBoard.push(boardRow);
  }
  return gameBoard;
};

var battleShipBoard = buildGameBoard(8);
<commit_msg>Changed Ships function to create different instances of ships<commit_after>
var startGame = function(){
  return false;
};

function Ship(shipSize,shipType){
  this.shipSize = shipSize || 0;
  this.shipType = shipType;
}
var submarine = new Ship(3, "Submarine");
var destroyer = new Ship(3,"Destroyer");
var patrolBoat = new Ship(2, "Patrol Boat");
var battleship = new Ship(4, "Battleship");
var aircraftCarrier = new Ship(5, "Aircraft Carrier");

var Players = function(){
  return false;
};

var Scoreboard = function(){
  return false;
};

var buildGameBoard = function(boardSize) {
  var gameBoard = [];

  for (var row = 0; row < boardSize; row++) {
    var boardRow = [];
    for (var column = 0; column < boardSize; column++) {
      // We are creating an Object (can create constructor in another location)
      var squareTile = {
        position: [row, column]
      };
      boardRow.push(squareTile);
    }
    gameBoard.push(boardRow);
  }
  return gameBoard;
};

var battleShipBoard = buildGameBoard(8);
<|endoftext|>


<commit_before>var KEYCODE_ESCAPE = 27;
var KEYCODE_BACKSPACE = 8;
var KEYCODE_ENTER = 13;
var KEYCODE_LEFT = 37;
var KEYCODE_UP = 38;
var KEYCODE_RIGHT = 39;
var KEYCODE_DOWN = 40;

// entityMap and escapeHtml are from https://github.com/janl/mustache.js
// Copyright (c) 2009 Chris Wanstrath (Ruby)
// Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
// Copyright (c) 2010-2015 The mustache.js community
var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": ''',
  '/': '/'
};
function escapeHtml(s) {
  return String(s).replace(/[&<>"'\/]/g, function fromEntityMap (s) {
    return entityMap[s];
  });
}

$().ready(function(){
  $('#buttons li:first').css('background-color', '#bbc').css('color', '#fff');

  var line = $('#line');
  var tip = $('#line_tip');
  line.hide();

  var infoport = $('#infoport');
  var stream = $('#stream');

  $(document).keypress(function(event){
    if (line.is(':hidden')) {
      tip.hide();
      line.show();
    }
    if (!line.is(':focus')) {
      line.val(line.val() + String.fromCharCode(event.which));
      line[0].scrollLeft = line[0].scrollWidth;
    }
  });

  tip.click(function(event){
    tip.hide();
    line.show();
    line.focus();
  });

  $(document).keydown(function(event){
    if (event.which == KEYCODE_ESCAPE) {
      line.val('');
      line.hide();
      tip.fadeIn();
    } else if (event.which == KEYCODE_ENTER) {
      var cmd = line.val();
      stream.prepend($('

').height(0).animate({
        height: '2em'
      }, 200, 'swing', function(){
        $(this).html(escapeHtml(cmd));
      }));
      line.fadeOut(400, function(){
        line.val('');
        tip.fadeIn();
      });
    } else if (!line.is(':focus')) {
      if (event.which == KEYCODE_BACKSPACE) {
        line.val(line.val().slice(0, -1));
        event.preventDefault();
      } else if (event.which == KEYCODE_LEFT) {
        // LEFT ONE TAB
      } else if (event.which == KEYCODE_RIGHT) {
        // RIGHT ONE TAB
      } else if (event.which == KEYCODE_UP) {
        infoport.animate({
          scrollTop: Math.max(0, infoport.scrollTop() - 60)
        }, 100);
      } else if (event.which == KEYCODE_DOWN) {
        infoport.animate({
          scrollTop: Math.min(infoport.scrollTop() + 60, infoport[0].scrollHeight - infoport[0].clientHeight)
        }, 100);
      }
    }
  });

  $(document).keyup(function(){
    if (line.val() == '') {
      line.hide();
      tip.fadeIn();
    }
  });
});
<commit_msg>Lean animations and prevent blank submits<commit_after>var KEYCODE_ESCAPE = 27;
var KEYCODE_BACKSPACE = 8;
var KEYCODE_ENTER = 13;
var KEYCODE_LEFT = 37;
var KEYCODE_UP = 38;
var KEYCODE_RIGHT = 39;
var KEYCODE_DOWN = 40;

// entityMap and escapeHtml are from https://github.com/janl/mustache.js
// Copyright (c) 2009 Chris Wanstrath (Ruby)
// Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
// Copyright (c) 2010-2015 The mustache.js community
var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": ''',
  '/': '/'
};
function escapeHtml(s) {
  return String(s).replace(/[&<>"'\/]/g, function fromEntityMap (s) {
    return entityMap[s];
  });
}

$().ready(function(){
  $('#buttons li:first').css('background-color', '#bbc').css('color', '#fff');

  var line = $('#line');
  var tip = $('#line_tip');
  line.hide();

  var infoport = $('#infoport');
  var stream = $('#stream');

  $(document).keypress(function(event){
    if (line.is(':hidden')) {
      tip.hide();
      line.show();
    }
    if (!line.is(':focus')) {
      line.val(line.val() + String.fromCharCode(event.which));
      line[0].scrollLeft = line[0].scrollWidth;
    }
  });

  tip.click(function(event){
    tip.hide();
    line.show();
    line.focus();
  });

  $(document).keydown(function(event){
    if (event.which == KEYCODE_ESCAPE) {
      line.val('');
      line.hide();
      tip.fadeIn();
    } else if (event.which == KEYCODE_ENTER) {
      var cmd = line.val();
      if (cmd) {
        stream.prepend($('

').height(0).animate({
          height: '2em'
        }, 200, 'swing', function(){
          $(this).html(escapeHtml(cmd));
        }));
        line.val('').hide();
        tip.show();
      }
    } else if (!line.is(':focus')) {
      if (event.which == KEYCODE_BACKSPACE) {
        line.val(line.val().slice(0, -1));
        event.preventDefault();
      } else if (event.which == KEYCODE_LEFT) {
        // LEFT ONE TAB
      } else if (event.which == KEYCODE_RIGHT) {
        // RIGHT ONE TAB
      } else if (event.which == KEYCODE_UP) {
        infoport.animate({
          scrollTop: Math.max(0, infoport.scrollTop() - 60)
        }, 100);
      } else if (event.which == KEYCODE_DOWN) {
        infoport.animate({
          scrollTop: Math.min(infoport.scrollTop() + 60, infoport[0].scrollHeight - infoport[0].clientHeight)
        }, 100);
      }
    }
  });

  $(document).keyup(function(){
    if (line.val() == '') {
      line.hide();
      tip.fadeIn();
    }
  });
});
<|endoftext|>


<commit_before>var ParaparaCanvas = require("./parapara-canvas");
var Frame = require("./frame");
var FrameServer = require("./frame-server");
var drawTools = require("./draw-tools");

var frameServer;
var colorPicker, lineWidthPicker;
document.addEventListener("DOMContentLoaded", function() {
  // document.body を引数にするのは超絶良くないが、
  // html を変える必要が有るため、後で直さなくてはならない
  frameServer = new FrameServer(document.body);
  colorPicker = new drawTools.ColorPicker(document.getElementById("menu-colors"));
  lineWidthPicker = new drawTools.LineWidthPicker(document.getElementById("menu-line-width"));
});
<commit_msg>UI上でのmenuの状態を変更できるmenu.jsを追加<commit_after>var ParaparaCanvas = require("./parapara-canvas");
var Frame = require("./frame");
var FrameServer = require("./frame-server");
var drawTools = require("./draw-tools");
var Menu = require("./menu");

var frameServer;
var colorPicker, lineWidthPicker;
var menu;
document.addEventListener("DOMContentLoaded", function() {
  // document.body を引数にするのは超絶良くないが、
  // html を変える必要が有るため、後で直さなくてはならない
  frameServer = new FrameServer(document.body);
  colorPicker = new drawTools.ColorPicker(document.getElementById("menu-colors"), "red");
  lineWidthPicker = new drawTools.LineWidthPicker(document.getElementById("menu-line-width"), 10);
  menu = new Menu();

  document.getElementById("menu-side-btn").addEventListener("click", function() {
    menu.toggleMenu();
  });
});
<|endoftext|>


<commit_before>var $ = jQuery.noConflict();

var barbellWeights = {
	"LB": [45, 35],
	"KG": [20, 15]
};

var plateWeights = {
	"LB": [2.5,   5, 10, 25, 35, 45],
	"KG": [  1, 2.5,  5, 10, 15, 20]
};

var warmupScheme = [
	{ reps: 5, percent: 40},
	{ reps: 3, percent: 67},
	{ reps: 2, percent: 80},
	{ reps: 1, percent: 90},
];

var BarbellView = function()
{
	var self = this;

	self.units = ko.observableArray([
        'LB', 'KG'
    ]);

	self.storageHandler = new StorageHandler();

	self.weightUnit = ko.observable(self.storageHandler.getWithDefault('weightUnit', 'LB'));

	self.weightUnit.subscribe(function(newValue) {
		//change barbell and plates to appropriate units
		self.barbellWeights(barbellWeights[newValue]);
		self.barbellWeight(barbellWeights[newValue][0]);
		self.plateWeights(plateWeights[newValue]);

		//restore available plates

		self.plateWeightsAvailable(self.storageHandler.getWithDefault('plateWeightsAvailable' + self.weightUnit(), plateWeights[self.weightUnit()], true));

		self.storageHandler.set('weightUnit', newValue);
	});

	//set barbell choices
	self.barbellWeights = ko.observableArray(barbellWeights[self.weightUnit()]);
	self.barbellWeight  = ko.observable(barbellWeights[self.weightUnit()][0]);
	self.barbellWeightDisplay = function(weight) {
		return weight + ' ' + self.weightUnit();
	}

	//set plate choices and check all initially
	self.plateWeights = ko.observableArray(plateWeights[self.weightUnit()]);
	self.plateWeightsAvailable = ko.observableArray(self.storageHandler.getWithDefault('plateWeightsAvailable' + self.weightUnit(), plateWeights[self.weightUnit()], true));

	self.plateWeightsAvailable.subscribe(function(newValue) {

		currentPlatesAvailable = self.storageHandler.getWithDefault('plateWeightsAvailable' + self.weightUnit(), plateWeights[self.weightUnit()], true)

		//prevent not having any plates
		if (newValue.length == 0 && currentPlatesAvailable.length == 1) {
			self.plateWeightsAvailable(currentPlatesAvailable);

			alert('Whatcha gonna lift, bro?');
		} else {
			self.storageHandler.set('plateWeightsAvailable' + self.weightUnit(), newValue, true);
		}
	});

	self.weightToCalculate = ko.observable();
	//auto calc on 3 digits
	self.weightToCalculate.subscribe(function(newValue) {

		weightLength = newValue.length;

		if (weightLength == 3) {
			self.calculateSets();
			self.isSelected(false);

		}
	});

	self.displayConfigurationsNumber = 3;
	self.showMoreConfigurations = function() { console.log()
		self.displayConfigurationsNumber = 10;
		self.weightConfigs(self.allWeightConfigs.slice(0, self.displayConfigurationsNumber));
	}

	self.allWeightConfigs = self.storageHandler.getWithDefault('weightConfigs', [], true);
	self.weightConfigs      = ko.observableArray(self.allWeightConfigs.slice(0, self.displayConfigurationsNumber));

	//console.log(self.weightConfigs());

	//for fractional plates
	self.plateClass = function(plateSize, unit, count) {
		return 'plate-' + String(plateSize).replace('.', '--') + unit + ' plate-count-' + count;
	};

	self.padAndReverse = function(plateArray, platePadding) {

		for (i = plateArray.length; i < platePadding; i++) {
			plateArray.push({
				size:  0,
				count: 0
			});
		}

		return plateArray.reverse();
	};

	self.isSelected = ko.observable(true);

	self.calculateSets = function() {
		if (self.weightToCalculate() == null || self.weightToCalculate() < self.barbellWeight()) {
			return false;
		}

		sets = [];

		//getSets()
		thisWarmupScheme = warmupScheme.slice(0);
		thisWarmupScheme.push({ percent:100, reps: 0 });
		//getSets()

		//determine how much padding we need to get sets at bottom of div
		maxPlates = 0;

		for (i = 0; i < thisWarmupScheme.length; i++) {
			weight = parseInt(self.weightToCalculate() * thisWarmupScheme[i].percent / 100);

			set         = self.calculateSet(weight);
			set.percent = thisWarmupScheme[i].percent
			set.reps    = thisWarmupScheme[i].reps,
			sets.push(set);

			maxPlates = set.plateConfiguration.length > maxPlates ? set.plateConfiguration.length : maxPlates;

		}

		//keep all plate configs (up to max amount constant)
		self.allWeightConfigs.unshift({
			unit:         self.weightUnit(),
			weight:       self.weightToCalculate(),
			additional:   sets[sets.length-1].additional,
			platePadding: maxPlates,
			sets:         sets
		});
		self.allWeightConfigs.slice(0, 20);
		//but only display so many
		self.weightConfigs(self.allWeightConfigs.slice(0, self.displayConfigurationsNumber));

		self.storageHandler.set('weightConfigs', self.allWeightConfigs, true);

		//return focus to input
		//self.isSelected(true);

	};

	self.calculateSet = function(weightToCalculate) {
		//console.log(weightToCalculate);
		left = weightToCalculate - self.barbellWeight();

		platesToUse = self.plateWeightsAvailable().slice(0);
		platesToUse.sort(function(a, b) { return a - b; });

		plateConfiguration = [];
		plateCount = 0;

		while (left > 0 && platesToUse.length > 0) {
			//go from heaviest to lightest
			plateSize = platesToUse[platesToUse.length - 1];
			//need a balanced bar
			weightToSubtract =  plateSize * 2;

			if (left - weightToSubtract >= 0) {
				left -= weightToSubtract;

				plateCount++;
				//console.log(plateCount + ' ' + plateSize);
			} else {
				platesToUse.pop();
			}

			if (plateCount > 0 && left - weightToSubtract < 0) {
				plateConfiguration.push(new PlateConfiguration(
					plateSize,
					plateCount
				));

				plateCount = 0;

			}

		}

		return new Set(
			weightToCalculate - left,
			left,
			plateConfiguration
		);

	};

	self.slideDownConfig = function(e) {
		if (e.nodeType === 1) {
			$(e).hide().slideDown();
		}
	}

	self.settingsVisible = ko.observable(true);
	self.toggleSettings = function(e) {
		self.settingsVisible(!self.settingsVisible());
	}

}

function PlateConfiguration(size, count) {
	this.size  = size;
	this.count = count;
}

function Set(displayWeight, additional, plateConfiguration) {
	this.displayWeight      = displayWeight;
	this.additional         = additional;
	this.plateConfiguration = plateConfiguration;
}

function StorageHandler()
{
	//this.
}

StorageHandler.prototype.isSupported = function()
{
	return typeof(Storage) !== 'undefined';
}

StorageHandler.prototype.getWithDefault = function(key, defaultValue, isArray)
{

	if (this.isSupported() && this.storageKeyExists(key)) {

		if (isArray) {
			return JSON.parse(localStorage[key]);
		} else {
			return localStorage[key];
		}
	} else {
		return defaultValue;
	}
}

StorageHandler.prototype.storageKeyExists = function(key)
{
	return typeof(localStorage[key]) !== 'undefined';
}

StorageHandler.prototype.set = function(key, value, isArray)
{

	if (this.isSupported()) {
		if (isArray) {
			value = JSON.stringify(value);
		}

		localStorage[key] = value;
	}
}

ko.applyBindings(new BarbellView());

//BarbellView.weightUnit('KG');
<commit_msg>hide settings pane by default<commit_after>var $ = jQuery.noConflict();

var barbellWeights = {
	"LB": [45, 35],
	"KG": [20, 15]
};

var plateWeights = {
	"LB": [2.5,   5, 10, 25, 35, 45],
	"KG": [  1, 2.5,  5, 10, 15, 20]
};

var warmupScheme = [
	{ reps: 5, percent: 40},
	{ reps: 3, percent: 67},
	{ reps: 2, percent: 80},
	{ reps: 1, percent: 90},
];

var BarbellView = function()
{
	var self = this;

	self.units = ko.observableArray([
        'LB', 'KG'
    ]);

	self.storageHandler = new StorageHandler();

	self.weightUnit = ko.observable(self.storageHandler.getWithDefault('weightUnit', 'LB'));

	self.weightUnit.subscribe(function(newValue) {
		//change barbell and plates to appropriate units
		self.barbellWeights(barbellWeights[newValue]);
		self.barbellWeight(barbellWeights[newValue][0]);
		self.plateWeights(plateWeights[newValue]);

		//restore available plates

		self.plateWeightsAvailable(self.storageHandler.getWithDefault('plateWeightsAvailable' + self.weightUnit(), plateWeights[self.weightUnit()], true));

		self.storageHandler.set('weightUnit', newValue);
	});

	//set barbell choices
	self.barbellWeights = ko.observableArray(barbellWeights[self.weightUnit()]);
	self.barbellWeight  = ko.observable(barbellWeights[self.weightUnit()][0]);
	self.barbellWeightDisplay = function(weight) {
		return weight + ' ' + self.weightUnit();
	}

	//set plate choices and check all initially
	self.plateWeights = ko.observableArray(plateWeights[self.weightUnit()]);
	self.plateWeightsAvailable = ko.observableArray(self.storageHandler.getWithDefault('plateWeightsAvailable' + self.weightUnit(), plateWeights[self.weightUnit()], true));

	self.plateWeightsAvailable.subscribe(function(newValue) {

		currentPlatesAvailable = self.storageHandler.getWithDefault('plateWeightsAvailable' + self.weightUnit(), plateWeights[self.weightUnit()], true)

		//prevent not having any plates
		if (newValue.length == 0 && currentPlatesAvailable.length == 1) {
			self.plateWeightsAvailable(currentPlatesAvailable);

			alert('Whatcha gonna lift, bro?');
		} else {
			self.storageHandler.set('plateWeightsAvailable' + self.weightUnit(), newValue, true);
		}
	});

	self.weightToCalculate = ko.observable();
	//auto calc on 3 digits
	self.weightToCalculate.subscribe(function(newValue) {

		weightLength = newValue.length;

		if (weightLength == 3) {
			self.calculateSets();
			self.isSelected(false);

		}
	});

	self.displayConfigurationsNumber = 3;
	self.showMoreConfigurations = function() { console.log()
		self.displayConfigurationsNumber = 10;
		self.weightConfigs(self.allWeightConfigs.slice(0, self.displayConfigurationsNumber));
	}

	self.allWeightConfigs = self.storageHandler.getWithDefault('weightConfigs', [], true);
	self.weightConfigs      = ko.observableArray(self.allWeightConfigs.slice(0, self.displayConfigurationsNumber));

	//console.log(self.weightConfigs());

	//for fractional plates
	self.plateClass = function(plateSize, unit, count) {
		return 'plate-' + String(plateSize).replace('.', '--') + unit + ' plate-count-' + count;
	};

	self.padAndReverse = function(plateArray, platePadding) {

		for (i = plateArray.length; i < platePadding; i++) {
			plateArray.push({
				size:  0,
				count: 0
			});
		}

		return plateArray.reverse();
	};

	self.isSelected = ko.observable(true);

	self.calculateSets = function() {
		if (self.weightToCalculate() == null || self.weightToCalculate() < self.barbellWeight()) {
			return false;
		}

		sets = [];

		//getSets()
		thisWarmupScheme = warmupScheme.slice(0);
		thisWarmupScheme.push({ percent:100, reps: 0 });
		//getSets()

		//determine how much padding we need to get sets at bottom of div
		maxPlates = 0;

		for (i = 0; i < thisWarmupScheme.length; i++) {
			weight = parseInt(self.weightToCalculate() * thisWarmupScheme[i].percent / 100);

			set         = self.calculateSet(weight);
			set.percent = thisWarmupScheme[i].percent
			set.reps    = thisWarmupScheme[i].reps,
			sets.push(set);

			maxPlates = set.plateConfiguration.length > maxPlates ? set.plateConfiguration.length : maxPlates;

		}

		//keep all plate configs (up to max amount constant)
		self.allWeightConfigs.unshift({
			unit:         self.weightUnit(),
			weight:       self.weightToCalculate(),
			additional:   sets[sets.length-1].additional,
			platePadding: maxPlates,
			sets:         sets
		});
		self.allWeightConfigs.slice(0, 20);
		//but only display so many
		self.weightConfigs(self.allWeightConfigs.slice(0, self.displayConfigurationsNumber));

		self.storageHandler.set('weightConfigs', self.allWeightConfigs, true);

		//return focus to input
		//self.isSelected(true);

	};

	self.calculateSet = function(weightToCalculate) {
		//console.log(weightToCalculate);
		left = weightToCalculate - self.barbellWeight();

		platesToUse = self.plateWeightsAvailable().slice(0);
		platesToUse.sort(function(a, b) { return a - b; });

		plateConfiguration = [];
		plateCount = 0;

		while (left > 0 && platesToUse.length > 0) {
			//go from heaviest to lightest
			plateSize = platesToUse[platesToUse.length - 1];
			//need a balanced bar
			weightToSubtract =  plateSize * 2;

			if (left - weightToSubtract >= 0) {
				left -= weightToSubtract;

				plateCount++;
				//console.log(plateCount + ' ' + plateSize);
			} else {
				platesToUse.pop();
			}

			if (plateCount > 0 && left - weightToSubtract < 0) {
				plateConfiguration.push(new PlateConfiguration(
					plateSize,
					plateCount
				));

				plateCount = 0;

			}

		}

		return new Set(
			weightToCalculate - left,
			left,
			plateConfiguration
		);

	};

	self.slideDownConfig = function(e) {
		if (e.nodeType === 1) {
			$(e).hide().slideDown();
		}
	}

	self.settingsVisible = ko.observable(false);
	self.toggleSettings = function(e) {
		self.settingsVisible(!self.settingsVisible());
	}

}

function PlateConfiguration(size, count) {
	this.size  = size;
	this.count = count;
}

function Set(displayWeight, additional, plateConfiguration) {
	this.displayWeight      = displayWeight;
	this.additional         = additional;
	this.plateConfiguration = plateConfiguration;
}

function StorageHandler()
{
	//this.
}

StorageHandler.prototype.isSupported = function()
{
	return typeof(Storage) !== 'undefined';
}

StorageHandler.prototype.getWithDefault = function(key, defaultValue, isArray)
{

	if (this.isSupported() && this.storageKeyExists(key)) {

		if (isArray) {
			return JSON.parse(localStorage[key]);
		} else {
			return localStorage[key];
		}
	} else {
		return defaultValue;
	}
}

StorageHandler.prototype.storageKeyExists = function(key)
{
	return typeof(localStorage[key]) !== 'undefined';
}

StorageHandler.prototype.set = function(key, value, isArray)
{

	if (this.isSupported()) {
		if (isArray) {
			value = JSON.stringify(value);
		}

		localStorage[key] = value;
	}
}

ko.applyBindings(new BarbellView());

//BarbellView.weightUnit('KG');
<|endoftext|>


<commit_before>/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:
 * `<img src="blank.gif" data-src="my_image.png" width="600" height="400" class="lazy">`
 *
 * @see https://css-tricks.com/snippets/javascript/lazy-loading-images/
 *
 */

!( function( factory ) {
 if ( typeof define === "function" && define.amd ) {
   define(factory );
 } else {
   factory( );
 }
}(function( ){

  // All images.
  var images            = []
    , defaultImg        = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=='
    , backgroundImages  = [];

  function loadImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-src');
    img.onload = function() {
      el.src = src;
      fn? fn.call(el) : null;
    }
    img.src = src;
  }

  function loadBackgroundImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-backgroundimage');
    img.onload = function() {
      el.style.backgroundImage = 'url(' + src + ')';
      fn? fn.call(el) : null;
    }
    img.src = src;
  }

  function elementInViewport(el) {
    var rect = el.getBoundingClientRect()

    // For invisible element.
    if (rect.top + rect.bottom + rect.left + rect.right + rect.height + rect.width === 0) {
      return false;
    }

    return (
       rect.top   >= 0
    // Pre load.
    && rect.top   <= ((window.innerHeight || document.documentElement.clientHeight) + 100)
    && rect.left  >= 0
    // Hide carousel except first image. Do not add equal sign.
    && rect.left  < (window.innerWidth || document.documentElement.clientWidth)
    )
  }

  function processScroll() {

    for (var i = 0; i < images.length; i++) {
      if (!images[i].lazyloaded && elementInViewport(images[i]) ) {
        loadImage(images[i], function () {
          this.lazyloaded = true;
          this.classList.remove('lazy');
        });
      }
    }

    for (var i = 0; i < backgroundImages.length; i++) {
      if (!backgroundImages[i].lazyloaded && elementInViewport(backgroundImages[i]) ) {
        loadBackgroundImage(backgroundImages[i], function () {
          this.lazyloaded = true;
          this.classList.remove('lazy');
        });
      }
    }
  }

  var init = function(reload) {

    // For:
    images      = Array.prototype.slice.apply(document.querySelectorAll('img.lazy'))
    for (var i = 0; i < images.length; i++)
      images[i].src = images[i].src || defaultImg;

    // For:
    // You should do it manualy before document trigger complete event.
    //
    // var imagesDelay = document.querySelectorAll('img.lazy.delay');
    // for (var i = 0; i < imagesDelay.length; i++) {
    //   imagesDelay[i].setAttribute('data-src', imagesDelay[i].src)
    //   imagesDelay[i].src = defaultImg;
    //   images.push(imagesDelay[i])
    // }

    // For:

    backgroundImages = Array.prototype.slice.apply(document.querySelectorAll('.lazy[data-backgroundimage]'))
    for (var i = 0; i < backgroundImages.length; i++)
      backgroundImages[i].style.backgroundImage = 'url(' + (backgroundImages[i].style.backgroundImage || defaultImg) + ')';

    processScroll();

    if (!reload) {
      window.addEventListener('scroll', processScroll);
      window.addEventListener('touchend', processScroll);
    }

  }

  // For dynamic dom. When inerst html to dom.
  document.addEventListener('lazyload-reload', function() {
    init(true)
  })

  document.addEventListener('reload', function () {
    init(true)
  })

  // Image should load after document is completed, not AS SOON AS POSSIBLE.
  if (document.readyState === 'complete') {
    init()
  } else {
    document.addEventListener('readystatechange', function(e) {
      if (document.readyState === 'complete') {
        init();
      }
    })
  }

}));
<commit_msg>Updated: Lazyload triggered by 'touchmove'<commit_after>/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:
 * `<img src="blank.gif" data-src="my_image.png" width="600" height="400" class="lazy">`
 *
 * @see https://css-tricks.com/snippets/javascript/lazy-loading-images/
 *
 */

!( function( factory ) {
 if ( typeof define === "function" && define.amd ) {
   define(factory );
 } else {
   factory( );
 }
}(function( ){

  // All images.
  var images            = []
    , defaultImg        = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=='
    , backgroundImages  = [];

  function loadImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-src');
    img.onload = function() {
      el.src = src;
      fn? fn.call(el) : null;
    }
    img.src = src;
  }

  function loadBackgroundImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-backgroundimage');
    img.onload = function() {
      el.style.backgroundImage = 'url(' + src + ')';
      fn? fn.call(el) : null;
    }
    img.src = src;
  }

  function elementInViewport(el) {
    var rect = el.getBoundingClientRect()

    // For invisible element.
    if (rect.top + rect.bottom + rect.left + rect.right + rect.height + rect.width === 0) {
      return false;
    }

    return (
       rect.top   >= 0
    // Pre load.
    && rect.top   <= ((window.innerHeight || document.documentElement.clientHeight) + 100)
    && rect.left  >= 0
    // Hide carousel except first image. Do not add equal sign.
    && rect.left  < (window.innerWidth || document.documentElement.clientWidth)
    )
  }

  function processScroll() {

    for (var i = 0; i < images.length; i++) {
      if (!images[i].lazyloaded && elementInViewport(images[i]) ) {
        loadImage(images[i], function () {
          this.lazyloaded = true;
          this.classList.remove('lazy');
        });
      }
    }

    for (var i = 0; i < backgroundImages.length; i++) {
      if (!backgroundImages[i].lazyloaded && elementInViewport(backgroundImages[i]) ) {
        loadBackgroundImage(backgroundImages[i], function () {
          this.lazyloaded = true;
          this.classList.remove('lazy');
        });
      }
    }
  }

  var init = function(reload) {

    // For:
    images      = Array.prototype.slice.apply(document.querySelectorAll('img.lazy'))
    for (var i = 0; i < images.length; i++)
      images[i].src = images[i].src || defaultImg;

    // For:
    // You should do it manualy before document trigger complete event.
    //
    // var imagesDelay = document.querySelectorAll('img.lazy.delay');
    // for (var i = 0; i < imagesDelay.length; i++) {
    //   imagesDelay[i].setAttribute('data-src', imagesDelay[i].src)
    //   imagesDelay[i].src = defaultImg;
    //   images.push(imagesDelay[i])
    // }

    // For:

    backgroundImages = Array.prototype.slice.apply(document.querySelectorAll('.lazy[data-backgroundimage]'))
    for (var i = 0; i < backgroundImages.length; i++)
      backgroundImages[i].style.backgroundImage = 'url(' + (backgroundImages[i].style.backgroundImage || defaultImg) + ')';

    processScroll();

    if (!reload) {
      window.addEventListener('scroll', processScroll);
      window.addEventListener('touchmove', processScroll);
    }

  }

  // For dynamic dom. When inerst html to dom.
  document.addEventListener('lazyload-reload', function() {
    init(true)
  })

  document.addEventListener('reload', function () {
    init(true)
  })

  // Image should load after document is completed, not AS SOON AS POSSIBLE.
  if (document.readyState === 'complete') {
    init()
  } else {
    document.addEventListener('readystatechange', function(e) {
      if (document.readyState === 'complete') {
        init();
      }
    })
  }

}));
<|endoftext|>


<commit_before>var params = processExpr(" ");
var ojob_shouldRun = true;
var ojob_args = {};

if (Object.keys(params).length == 1 && Object.keys(params)[0] == "") ojob_showHelp();

// Check parameters
if (isDef(params["-h"]) && params["-h"] == "") {
	delete params["-h"];
	ojob_showHelp();
}

if (isDef(params["-compile"]) && params["-compile"] == "") {
	delete params["-compile"];
	ojob_compile();
}

if (isDef(params["-tojson"]) && params["-tojson"] == "") {
	delete params["-tojson"];
	ojob_tojson();
}

if (isDef(params["-jobs"]) && params["-jobs"] == "") {
	delete params["-jobs"];
	ojob_jobs();
}

if (isDef(params["-todo"]) && params["-todo"] == "") {
	delete params["-todo"];
	ojob_todo();
}

if (isDef(params["-deps"]) && params["-deps"] == "") {
	delete params["-deps"];
	ojob_draw();
}

if (isDef(params["-jobhelp"]) && params["-jobhelp"] == "") {
	delete params["-jobhelp"];
	ojob_jobhelp();
}

//if ($from(Object.keys(params)).starts("-").any()) {
//	$from(Object.keys(params)).starts("-").select(function(r) {
//		ojob_args[r.replace(/^-/, "")] = params[r];
//		delete params[r];
//	});
//}

if (Object.keys(params).length >= 1 && ojob_shouldRun) {
	ojob_runFile();
}

function ojob_showHelp() {
	print("Usage: ojob aYamlFile.yaml/json [options]\n");
	print("  -compile       Compile all includes and current file into a single yaml output.");
	print("  -tojson        Outputs all includes and current file into a single json output.");
	print("  -jobs          List all jobs available.");
	print("  -todo          List the final todo list.");
	print("  -deps          Draws a list of dependencies of todo jobs on a file.");
	print("  -jobhelp (job) Display any available help information for a job.");
	print("");
	print("(version " + af.getVersion() + ", " + Packages.openaf.AFCmdBase.LICENSE +")");
	ojob_shouldRun = false;
}

function ojob__getFile() {
	var ks = Object.keys(params);
	if (ks.length >= 1) {
		var f = ks[0];
		delete params[f];
		return f;
	} else {
		printErr("Didn't recognize the aYamlFile.yaml\n");
		ojob_showHelp();
		return undefined;
	}
}

function ojob_compile() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML(ow.loadOJob().previewFile(file)));
	}
	ojob_shouldRun = false;
}

function ojob_tojson() {
	var file = ojob__getFile();

	if (isDef(file)) {
		sprint(ow.loadOJob().previewFile(file));
	}
	ojob_shouldRun = false;
}

function ojob_jobs() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML($stream(ow.loadOJob().previewFile(file).jobs).map("name").distinct().toArray().sort()));
	}
	ojob_shouldRun = false;
}

function ojob_draw() {
	var file = ojob__getFile();
	ow.loadOJob();

	var oj = ow.oJob.previewFile(file);

	function getDeps(aJobName) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(j)) return undefined;

		if (isDef(j.deps)) {
			return j.deps;
		} else {
			return [];
		}
	}

	function getPaths(aJobName, res) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(res)) res = {
			from: [],
			to  : []
		};

		if (isUnDef(j)) return res;

		res = {
			to  : res.to.concat(j.to),
			from: res.from.concat(j.from)
		};

		res = getPaths(j.from, res);
		res = getPaths(j.to, res);

		return res;
	}

	function getPath(aJobName) {
		var msg = "";

		var deps = getDeps(aJobName);
		if (isUnDef(deps)) {
			msg += "!!NOT FOUND!!";
		} else {
			for(var i in deps) {
				var dep = (isDef(deps[i].name)) ? deps[i].name : deps[i];
				msg += " :" + dep;
				var r = getPath(dep);
				if (r.length > 0) {
					msg += " (" + r + ")";
				}
			}

		}

		return msg;
	}

	if (oj.ojob.sequential) {
		print("Sequential dependencies are enabled.\n");
	}

	ansiStart();
	print(ansiColor("bold,underline", "\nDependencies:"));
	$from(oj.todo).select(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		printnl("[" + ansiColor("bold", nn) + "]");
		var deps = getDeps(nn);
		print(getPath(nn));
	});

	print(ansiColor("bold,underline", "\nPaths:"));
	$from(oj.todo).select(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		var paths = getPaths(nn);
		var msg = "";
		for (var i in paths.from) {
			msg += (isDef(paths.from[i]) ? paths.from[i] + " -> " : "");
		}
		msg += "[" + ansiColor("bold", nn) + "]";
		for (var i in paths.to) {
			msg += (isDef(paths.to[i]) ? " -> " + paths.to[i] : "");
		}
		print(msg);
	});
	ansiStop();

	ojob_shouldRun = false;
}

function ojob_jobhelp() {
	var file = ojob__getFile();

	var ks = Object.keys(params);
	var job = "";
	if (ks.length >= 1) {
		job = ks[0];
		delete params[job];
	} else {
		printErr("Didn't recognize the job to try to obtain help from.\n");
		ojob_showHelp();
		return undefined;
	}

	if (isDef(file)) {
		var hh = $from(ow.loadOJob().previewFile(file).jobs).equals("name", job).select({"name":"n/a", "help": "n/a"})[0];
		if (isDef(hh)) {
			print(hh.name);
			print(repeat(hh.name.length, '-'));
			print("");
			print(hh.help);
		} else {
                   	printErr("Didn't find job help for '" + job + "'.");
                        return undefined;
                }
	}
	ojob_shouldRun = false;
}

function ojob_todo() {
	var file = ojob__getFile();

	if (isDef(file)) {
		var l = ow.loadOJob().previewFile(file).todo;
		var r = [];
		for(var i in l) {
			if (isObject(l[i]))
				r.push(l[i].name);
			else
				r.push(l[i]);
		}
		print(af.toYAML(r));
	}
	ojob_shouldRun = false;
}

function ojob_runFile() {
	if (ojob_shouldRun) {
		var file = ojob__getFile();

		__expr = $from(params).select(function(r) { var rr={}; var kk = Object.keys(r)[0]; return kk+"="+r[kk]; }).join(" ");

		if (isDef(file)) {
			oJobRunFile(file, ojob_args);
		}
	}
}
<commit_msg>Improving ojob jobhelp parameter<commit_after>var params = processExpr(" ");
var ojob_shouldRun = true;
var ojob_args = {};

if (Object.keys(params).length == 1 && Object.keys(params)[0] == "") ojob_showHelp();

// Check parameters
if (isDef(params["-h"]) && params["-h"] == "") {
	delete params["-h"];
	ojob_showHelp();
}

if (isDef(params["-compile"]) && params["-compile"] == "") {
	delete params["-compile"];
	ojob_compile();
}

if (isDef(params["-tojson"]) && params["-tojson"] == "") {
	delete params["-tojson"];
	ojob_tojson();
}

if (isDef(params["-jobs"]) && params["-jobs"] == "") {
	delete params["-jobs"];
	ojob_jobs();
}

if (isDef(params["-todo"]) && params["-todo"] == "") {
	delete params["-todo"];
	ojob_todo();
}

if (isDef(params["-deps"]) && params["-deps"] == "") {
	delete params["-deps"];
	ojob_draw();
}

if (isDef(params["-jobhelp"]) && params["-jobhelp"] == "") {
	delete params["-jobhelp"];
	ojob_jobhelp();
}

//if ($from(Object.keys(params)).starts("-").any()) {
//	$from(Object.keys(params)).starts("-").select(function(r) {
//		ojob_args[r.replace(/^-/, "")] = params[r];
//		delete params[r];
//	});
//}

if (Object.keys(params).length >= 1 && ojob_shouldRun) {
	ojob_runFile();
}

function ojob_showHelp() {
	print("Usage: ojob aYamlFile.yaml/json [options]\n");
	print("  -compile       Compile all includes and current file into a single yaml output.");
	print("  -tojson        Outputs all includes and current file into a single json output.");
	print("  -jobs          List all jobs available.");
	print("  -todo          List the final todo list.");
	print("  -deps          Draws a list of dependencies of todo jobs on a file.");
	print("  -jobhelp (job) Display any available help information for a job.");
	print("");
	print("(version " + af.getVersion() + ", " + Packages.openaf.AFCmdBase.LICENSE +")");
	ojob_shouldRun = false;
}

function ojob__getFile() {
	var ks = Object.keys(params);
	if (ks.length >= 1) {
		var f = ks[0];
		delete params[f];
		return f;
	} else {
		printErr("Didn't recognize the aYamlFile.yaml\n");
		ojob_showHelp();
		return undefined;
	}
}

function ojob_compile() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML(ow.loadOJob().previewFile(file)));
	}
	ojob_shouldRun = false;
}

function ojob_tojson() {
	var file = ojob__getFile();

	if (isDef(file)) {
		sprint(ow.loadOJob().previewFile(file));
	}
	ojob_shouldRun = false;
}

function ojob_jobs() {
	var file = ojob__getFile();

	if (isDef(file)) {
		print(af.toYAML($stream(ow.loadOJob().previewFile(file).jobs).map("name").distinct().toArray().sort()));
	}
	ojob_shouldRun = false;
}

function ojob_draw() {
	var file = ojob__getFile();
	ow.loadOJob();

	var oj = ow.oJob.previewFile(file);

	function getDeps(aJobName) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(j)) return undefined;

		if (isDef(j.deps)) {
			return j.deps;
		} else {
			return [];
		}
	}

	function getPaths(aJobName, res) {
		var j = $from(oj.jobs).equals("name", aJobName).first();

		if (isUnDef(res)) res = {
			from: [],
			to  : []
		};

		if (isUnDef(j)) return res;

		res = {
			to  : res.to.concat(j.to),
			from: res.from.concat(j.from)
		};

		res = getPaths(j.from, res);
		res = getPaths(j.to, res);

		return res;
	}

	function getPath(aJobName) {
		var msg = "";

		var deps = getDeps(aJobName);
		if (isUnDef(deps)) {
			msg += "!!NOT FOUND!!";
		} else {
			for(var i in deps) {
				var dep = (isDef(deps[i].name)) ? deps[i].name : deps[i];
				msg += " :" + dep;
				var r = getPath(dep);
				if (r.length > 0) {
					msg += " (" + r + ")";
				}
			}

		}

		return msg;
	}

	if (oj.ojob.sequential) {
		print("Sequential dependencies are enabled.\n");
	}

	ansiStart();
	print(ansiColor("bold,underline", "\nDependencies:"));
	$from(oj.todo).select(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		printnl("[" + ansiColor("bold", nn) + "]");
		var deps = getDeps(nn);
		print(getPath(nn));
	});

	print(ansiColor("bold,underline", "\nPaths:"));
	$from(oj.todo).select(function(v) {
		var nn = (isDef(v.name) ? v.name : v);
		var paths = getPaths(nn);
		var msg = "";
		for (var i in paths.from) {
			msg += (isDef(paths.from[i]) ? paths.from[i] + " -> " : "");
		}
		msg += "[" + ansiColor("bold", nn) + "]";
		for (var i in paths.to) {
			msg += (isDef(paths.to[i]) ? " -> " + paths.to[i] : "");
		}
		print(msg);
	});
	ansiStop();

	ojob_shouldRun = false;
}

function ojob_jobhelp() {
	var file = ojob__getFile();

	//var ks = Object.keys(params);
	var job = String(__expr).replace(/.+-jobhelp +/i, "");
	if (job != "") {
		params = [];
	} else {
		printErr("Didn't recognize the job to try to obtain help from.\n");
		ojob_showHelp();
		return undefined;
	}

	if (isDef(file)) {
		var hh = $from(ow.loadOJob().previewFile(file).jobs).equals("name", job).select({"name":"n/a", "help": "n/a"})[0];
		if (isDef(hh)) {
			print(hh.name);
			print(repeat(hh.name.length, '-'));
			print("");
			print(hh.help);
		} else {
                   	printErr("Didn't find job help for '" + job + "'.");
                        return undefined;
                }
	}
	ojob_shouldRun = false;
}

function ojob_todo() {
	var file = ojob__getFile();

	if (isDef(file)) {
		var l = ow.loadOJob().previewFile(file).todo;
		var r = [];
		for(var i in l) {
			if (isObject(l[i]))
				r.push(l[i].name);
			else
				r.push(l[i]);
		}
		print(af.toYAML(r));
	}
	ojob_shouldRun = false;
}

function ojob_runFile() {
	if (ojob_shouldRun) {
		var file = ojob__getFile();

		__expr = $from(params).select(function(r) { var rr={}; var kk = Object.keys(r)[0]; return kk+"="+r[kk]; }).join(" ");

		if (isDef(file)) {
			oJobRunFile(file, ojob_args);
		}
	}
}
<|endoftext|>


<commit_before>export default {
  name: 'mdi',
  type: {
    positive: 'mdi-check-circle',
    negative: 'mdi-alert',
    info: 'mdi-info',
    warning: 'mdi-priority-high'
  },
  arrow: {
    up: 'mdi-arrow-upward',
    right: 'mdi-arrow-forward',
    down: 'mdi-arrow-downward',
    left: 'mdi-arrow-back'
  },
  chevron: {
    left: 'mdi-chevron-left',
    right: 'mdi-chevron-right'
  },

  pullToRefresh: {
    arrow: 'mdi-arrow-downward',
    refresh: 'mdi-refresh'
  },
  search: {
    icon: 'mdi-magnify',
    clear: 'mdi-close-circle',
    clearInverted: 'mdi-close'
  },
  carousel: {
    left: 'mdi-chevron-left',
    right: 'mdi-chevron-right',
    quickNav: 'mdi-circle'
  },
  checkbox: {
    checked: {
      ios: 'mdi-checkbox-marked-circle',
      mat: 'mdi-checkbox-marked'
    },
    unchecked: {
      ios: 'mdi-checkbox-blank-circle-outline',
      mat: 'mdi-checkbox-blank-outline'
    },
    indeterminate: {
      ios: 'mdi-minus-circle-outline',
      mat: 'mdi-minus-box'
    }
  },
  chip: {
    close: 'mdi-close-circle'
  },
  chipsInput: {
    add: 'mdi-send'
  },
  collapsible: {
    icon: 'mdi-chevron-down'
  },
  datetime: {
    arrowLeft: 'mdi-chevron-left',
    arrowRight: 'mdi-chevron-right'
  },
  editor: {
    bold: 'mdi-format-bold',
    italic: 'mdi-format-italic',
    strikethrough: 'mdi-format-strikethrough-variant',
    underline: 'mdi-format-underline',
    unorderedList: 'mdi-format-list-bulleted',
    orderedList: 'mdi-format-list-numbers',
    subscript: 'mdi-format-subscript',
    superscript: 'mdi-format-superscript',
    hyperlink: 'mdi-link',
    toggleFullscreen: 'mdi-fullscreen',
    quote: 'mdi-format-quote-close',
    left: 'mdi-format-align-left',
    center: 'mdi-format-align-center',
    right: 'mdi-format-align-right',
    justify: 'mdi-format-align-justify',
    print: 'mdi-printer',
    outdent: 'mdi-format-indent-decrease',
    indent: 'mdi-format-indent-increase',
    removeFormat: 'mdi-format-clear',
    formatting: 'mdi-format-color-text',
    fontSize: 'mdi-format-size',
    align: 'mdi-format-align-left',
    hr: 'mdi-minus',
    undo: 'mdi-undo',
    redo: 'mdi-redo',
    header: 'mdi-format-size',
    code: 'mdi-code',
    size: 'mdi-format-size',
    font: 'mdi-format-font'
  },
  fab: {
    icon: 'mdi-add',
    activeIcon: 'mdi-close'
  },
  input: {
    showPass: 'mdi-eye',
    hidePass: 'mdi-eye-off',
    showNumber: 'mdi-keyboard',
    hideNumber: 'mdi-keyboard-close',
    clear: 'mdi-close-circle',
    clearInverted: 'mdi-close',
    dropdown: 'mdi-menu-down'
  },
  pagination: {
    first: 'mdi-page-first',
    prev: 'mdi-chevron-left',
    next: 'mdi-chevron-right',
    last: 'mdi-page-last'
  },
  radio: {
    checked: {
      ios: 'mdi-check',
      mat: 'mdi-radiobox-marked'
    },
    unchecked: {
      ios: '',
      mat: 'mdi-radiobox-blank'
    }
  },
  rating: {
    icon: 'mdi-star'
  },
  stepper: {
    done: 'mdi-check',
    active: 'mdi-pencil',
    error: 'mdi-alert'
  },
  tabs: {
    left: 'mdi-chevron-left',
    right: 'mdi-chevron-right'
  },
  table: {
    arrowUp: 'mdi-arrow-upward',
    warning: 'mdi-alert',
    prevPage: 'mdi-chevron-left',
    nextPage: 'mdi-chevron-right'
  },
  tree: {
    icon: 'mdi-play'
  },
  uploader: {
    done: 'mdi-done',
    clear: 'mdi-close-circle',
    clearInverted: 'mdi-close',
    add: 'mdi-plus',
    upload: 'mdi-cloud-upload',
    expand: 'mdi-chevron-down',
    file: 'mdi-file'
  }
}
<commit_msg>Correct warning icon (#1608)<commit_after>export default {
  name: 'mdi',
  type: {
    positive: 'mdi-check-circle',
    negative: 'mdi-alert',
    info: 'mdi-info',
    warning: 'mdi-exclamation'
  },
  arrow: {
    up: 'mdi-arrow-upward',
    right: 'mdi-arrow-forward',
    down: 'mdi-arrow-downward',
    left: 'mdi-arrow-back'
  },
  chevron: {
    left: 'mdi-chevron-left',
    right: 'mdi-chevron-right'
  },

  pullToRefresh: {
    arrow: 'mdi-arrow-downward',
    refresh: 'mdi-refresh'
  },
  search: {
    icon: 'mdi-magnify',
    clear: 'mdi-close-circle',
    clearInverted: 'mdi-close'
  },
  carousel: {
    left: 'mdi-chevron-left',
    right: 'mdi-chevron-right',
    quickNav: 'mdi-circle'
  },
  checkbox: {
    checked: {
      ios: 'mdi-checkbox-marked-circle',
      mat: 'mdi-checkbox-marked'
    },
    unchecked: {
      ios: 'mdi-checkbox-blank-circle-outline',
      mat: 'mdi-checkbox-blank-outline'
    },
    indeterminate: {
      ios: 'mdi-minus-circle-outline',
      mat: 'mdi-minus-box'
    }
  },
  chip: {
    close: 'mdi-close-circle'
  },
  chipsInput: {
    add: 'mdi-send'
  },
  collapsible: {
    icon: 'mdi-chevron-down'
  },
  datetime: {
    arrowLeft: 'mdi-chevron-left',
    arrowRight: 'mdi-chevron-right'
  },
  editor: {
    bold: 'mdi-format-bold',
    italic: 'mdi-format-italic',
    strikethrough: 'mdi-format-strikethrough-variant',
    underline: 'mdi-format-underline',
    unorderedList: 'mdi-format-list-bulleted',
    orderedList: 'mdi-format-list-numbers',
    subscript: 'mdi-format-subscript',
    superscript: 'mdi-format-superscript',
    hyperlink: 'mdi-link',
    toggleFullscreen: 'mdi-fullscreen',
    quote: 'mdi-format-quote-close',
    left: 'mdi-format-align-left',
    center: 'mdi-format-align-center',
    right: 'mdi-format-align-right',
    justify: 'mdi-format-align-justify',
    print: 'mdi-printer',
    outdent: 'mdi-format-indent-decrease',
    indent: 'mdi-format-indent-increase',
    removeFormat: 'mdi-format-clear',
    formatting: 'mdi-format-color-text',
    fontSize: 'mdi-format-size',
    align: 'mdi-format-align-left',
    hr: 'mdi-minus',
    undo: 'mdi-undo',
    redo: 'mdi-redo',
    header: 'mdi-format-size',
    code: 'mdi-code',
    size: 'mdi-format-size',
    font: 'mdi-format-font'
  },
  fab: {
    icon: 'mdi-add',
    activeIcon: 'mdi-close'
  },
  input: {
    showPass: 'mdi-eye',
    hidePass: 'mdi-eye-off',
    showNumber: 'mdi-keyboard',
    hideNumber: 'mdi-keyboard-close',
    clear: 'mdi-close-circle',
    clearInverted: 'mdi-close',
    dropdown: 'mdi-menu-down'
  },
  pagination: {
    first: 'mdi-page-first',
    prev: 'mdi-chevron-left',
    next: 'mdi-chevron-right',
    last: 'mdi-page-last'
  },
  radio: {
    checked: {
      ios: 'mdi-check',
      mat: 'mdi-radiobox-marked'
    },
    unchecked: {
      ios: '',
      mat: 'mdi-radiobox-blank'
    }
  },
  rating: {
    icon: 'mdi-star'
  },
  stepper: {
    done: 'mdi-check',
    active: 'mdi-pencil',
    error: 'mdi-alert'
  },
  tabs: {
    left: 'mdi-chevron-left',
    right: 'mdi-chevron-right'
  },
  table: {
    arrowUp: 'mdi-arrow-upward',
    warning: 'mdi-alert',
    prevPage: 'mdi-chevron-left',
    nextPage: 'mdi-chevron-right'
  },
  tree: {
    icon: 'mdi-play'
  },
  uploader: {
    done: 'mdi-done',
    clear: 'mdi-close-circle',
    clearInverted: 'mdi-close',
    add: 'mdi-plus',
    upload: 'mdi-cloud-upload',
    expand: 'mdi-chevron-down',
    file: 'mdi-file'
  }
}
<|endoftext|>


<commit_before>'use strict';

function Panner(context) {
    var node = context.createPanner();
    // Default for stereo is 'HRTF' can also be 'equalpower'
    node.panningModel = Panner.defaults.panningModel;

    // Distance model and attributes
    // Can be 'linear' 'inverse' 'exponential'
    node.distanceModel = Panner.defaults.distanceModel;
    node.refDistance = Panner.defaults.refDistance;
    node.maxDistance = Panner.defaults.maxDistance;
    node.rolloffFactor = Panner.defaults.rolloffFactor;
    node.coneInnerAngle = Panner.defaults.coneInnerAngle;
    node.coneOuterAngle = Panner.defaults.coneOuterAngle;
    node.coneOuterGain = Panner.defaults.coneOuterGain;

    // simple vec3 object pool
    var VecPool = {
        pool: [],
        get: function(x, y, z) {
            var v = this.pool.length ? this.pool.pop() : { x: 0, y: 0, z: 0 };
            // check if a vector has been passed in
            if(x !== undefined && isNaN(x) && 'x' in x && 'y' in x && 'z' in x) {
                v.x = x.x || 0;
                v.y = x.y || 0;
                v.z = x.z || 0;
            }
            else {
                v.x = x || 0;
                v.y = y || 0;
                v.z = z || 0;
            }
            return v;
        },
        dispose: function(instance) {
            this.pool.push(instance);
        }
    };

    var globalUp = VecPool.get(0, 1, 0);

    var setOrientation = function(node, fw) {
        // set the orientation of the source (where the audio is coming from)

        // calculate up vec ( up = (forward cross (0, 1, 0)) cross forward )
        var up = VecPool.get(fw.x, fw.y, fw.z);
        cross(up, globalUp);
        cross(up, fw);
        normalize(up);
        normalize(fw);
        // set the audio context's listener position to match the camera position
        node.setOrientation(fw.x, fw.y, fw.z, up.x, up.y, up.z);

        // return the vecs to the pool
        VecPool.dispose(fw);
        VecPool.dispose(up);
    };

    var setPosition = function(node, vec) {
        node.setPosition(vec.x, vec.y, vec.z);
        VecPool.dispose(vec);
    };

    var setVelocity = function(node, vec) {
        node.setVelocity(vec.x, vec.y, vec.z);
        VecPool.dispose(vec);
    };

    // cross product of 2 vectors
    var cross = function ( a, b ) {
        var ax = a.x, ay = a.y, az = a.z;
        var bx = b.x, by = b.y, bz = b.z;
        a.x = ay * bz - az * by;
        a.y = az * bx - ax * bz;
        a.z = ax * by - ay * bx;
    };

    // normalise to unit vector
    var normalize = function (vec3) {
        if(vec3.x === 0 && vec3.y === 0 && vec3.z === 0) {
            return vec3;
        }
        var length = Math.sqrt( vec3.x * vec3.x + vec3.y * vec3.y + vec3.z * vec3.z );
        var invScalar = 1 / length;
        vec3.x *= invScalar;
        vec3.y *= invScalar;
        vec3.z *= invScalar;
        return vec3;
    };

    // pan left to right with value from -1 to 1
    // creates a nice curve with z
    node.setX = function(value) {
        var deg45 = Math.PI / 4,
            deg90 = deg45 * 2,
            x = value * deg45,
            z = x + deg90;

        if (z > deg90) {
            z = Math.PI - z;
        }

        x = Math.sin(x);
        z = Math.sin(z);

        node.setPosition(x, 0, z);
    };

    /*var x = 0,
        y = 0,
        z = 0;

    Object.defineProperties(node, {
        'x': {
            get: function() { return x; },
            set: function(value) {
                x = value;
                node.setPosition(x, y, z);
            }
        }
    });*/

    // set the position the audio is coming from)
    node.setSourcePosition = function(x, y, z) {
        setPosition(node, VecPool.get(x, y, z));
    };

    // set the direction the audio is coming from)
    node.setSourceOrientation = function(x, y, z) {
        setOrientation(node, VecPool.get(x, y, z));
    };

    // set the veloicty of the audio source (if moving)
    node.setSourceVelocity = function(x, y, z) {
        setVelocity(node, VecPool.get(x, y, z));
    };

    // set the position of who or what is hearing the audio (could be camera or some character)
    node.setListenerPosition = function(x, y, z) {
        setPosition(context.listener, VecPool.get(x, y, z));
    };

    // set the position of who or what is hearing the audio (could be camera or some character)
    node.setListenerOrientation = function(x, y, z) {
        setOrientation(context.listener, VecPool.get(x, y, z));
    };

    // set the velocity (if moving) of who or what is hearing the audio (could be camera or some character)
    node.setListenerVelocity = function(x, y, z) {
        setVelocity(context.listener, VecPool.get(x, y, z));
    };

    // helper to calculate velocity
    node.calculateVelocity = function(currentPosition, lastPosition, deltaTime) {
        var dx = currentPosition.x - lastPosition.x;
        var dy = currentPosition.y - lastPosition.y;
        var dz = currentPosition.z - lastPosition.z;
        return VecPool.get(dx / deltaTime, dy / deltaTime, dz / deltaTime);
    };

    node.setDefaults = function(defaults) {
        Object.keys(defaults).forEach(function(key) {
            Panner.defaults[key] = defaults[key];
        });
    };

    return node;
}

Panner.defaults = {
    panningModel: 'HRTF',
    distanceModel: 'linear',
    refDistance: 1,
    maxDistance: 1000,
    rolloffFactor: 1,
    coneInnerAngle: 360,
    coneOuterAngle: 0,
    coneOuterGain: 0
};

module.exports = Panner;
<commit_msg>set panner default position and orientation to fix new Firefox bug<commit_after>'use strict';

function Panner(context) {
    var node = context.createPanner();
    // Default for stereo is 'HRTF' can also be 'equalpower'
    node.panningModel = Panner.defaults.panningModel;

    // Distance model and attributes
    // Can be 'linear' 'inverse' 'exponential'
    node.distanceModel = Panner.defaults.distanceModel;
    node.refDistance = Panner.defaults.refDistance;
    node.maxDistance = Panner.defaults.maxDistance;
    node.rolloffFactor = Panner.defaults.rolloffFactor;
    node.coneInnerAngle = Panner.defaults.coneInnerAngle;
    node.coneOuterAngle = Panner.defaults.coneOuterAngle;
    node.coneOuterGain = Panner.defaults.coneOuterGain;
    // set to defaults (needed in Firefox)
    node.setPosition(0, 0, 0);
    node.setOrientation(0, 0, 0);

    // simple vec3 object pool
    var VecPool = {
        pool: [],
        get: function(x, y, z) {
            var v = this.pool.length ? this.pool.pop() : { x: 0, y: 0, z: 0 };
            // check if a vector has been passed in
            if(x !== undefined && isNaN(x) && 'x' in x && 'y' in x && 'z' in x) {
                v.x = x.x || 0;
                v.y = x.y || 0;
                v.z = x.z || 0;
            }
            else {
                v.x = x || 0;
                v.y = y || 0;
                v.z = z || 0;
            }
            return v;
        },
        dispose: function(instance) {
            this.pool.push(instance);
        }
    };

    var globalUp = VecPool.get(0, 1, 0);

    var setOrientation = function(node, fw) {
        // set the orientation of the source (where the audio is coming from)

        // calculate up vec ( up = (forward cross (0, 1, 0)) cross forward )
        var up = VecPool.get(fw.x, fw.y, fw.z);
        cross(up, globalUp);
        cross(up, fw);
        normalize(up);
        normalize(fw);
        // set the audio context's listener position to match the camera position
        node.setOrientation(fw.x, fw.y, fw.z, up.x, up.y, up.z);

        // return the vecs to the pool
        VecPool.dispose(fw);
        VecPool.dispose(up);
    };

    var setPosition = function(node, vec) {
        node.setPosition(vec.x, vec.y, vec.z);
        VecPool.dispose(vec);
    };

    var setVelocity = function(node, vec) {
        node.setVelocity(vec.x, vec.y, vec.z);
        VecPool.dispose(vec);
    };

    // cross product of 2 vectors
    var cross = function ( a, b ) {
        var ax = a.x, ay = a.y, az = a.z;
        var bx = b.x, by = b.y, bz = b.z;
        a.x = ay * bz - az * by;
        a.y = az * bx - ax * bz;
        a.z = ax * by - ay * bx;
    };

    // normalise to unit vector
    var normalize = function (vec3) {
        if(vec3.x === 0 && vec3.y === 0 && vec3.z === 0) {
            return vec3;
        }
        var length = Math.sqrt( vec3.x * vec3.x + vec3.y * vec3.y + vec3.z * vec3.z );
        var invScalar = 1 / length;
        vec3.x *= invScalar;
        vec3.y *= invScalar;
        vec3.z *= invScalar;
        return vec3;
    };

    // pan left to right with value from -1 to 1
    // creates a nice curve with z
    node.setX = function(value) {
        var deg45 = Math.PI / 4,
            deg90 = deg45 * 2,
            x = value * deg45,
            z = x + deg90;

        if (z > deg90) {
            z = Math.PI - z;
        }

        x = Math.sin(x);
        z = Math.sin(z);

        node.setPosition(x, 0, z);
    };

    /*var x = 0,
        y = 0,
        z = 0;

    Object.defineProperties(node, {
        'x': {
            get: function() { return x; },
            set: function(value) {
                x = value;
                node.setPosition(x, y, z);
            }
        }
    });*/

    // set the position the audio is coming from)
    node.setSourcePosition = function(x, y, z) {
        setPosition(node, VecPool.get(x, y, z));
    };

    // set the direction the audio is coming from)
    node.setSourceOrientation = function(x, y, z) {
        setOrientation(node, VecPool.get(x, y, z));
    };

    // set the veloicty of the audio source (if moving)
    node.setSourceVelocity = function(x, y, z) {
        setVelocity(node, VecPool.get(x, y, z));
    };

    // set the position of who or what is hearing the audio (could be camera or some character)
    node.setListenerPosition = function(x, y, z) {
        setPosition(context.listener, VecPool.get(x, y, z));
    };

    // set the position of who or what is hearing the audio (could be camera or some character)
    node.setListenerOrientation = function(x, y, z) {
        setOrientation(context.listener, VecPool.get(x, y, z));
    };

    // set the velocity (if moving) of who or what is hearing the audio (could be camera or some character)
    node.setListenerVelocity = function(x, y, z) {
        setVelocity(context.listener, VecPool.get(x, y, z));
    };

    // helper to calculate velocity
    node.calculateVelocity = function(currentPosition, lastPosition, deltaTime) {
        var dx = currentPosition.x - lastPosition.x;
        var dy = currentPosition.y - lastPosition.y;
        var dz = currentPosition.z - lastPosition.z;
        return VecPool.get(dx / deltaTime, dy / deltaTime, dz / deltaTime);
    };

    node.setDefaults = function(defaults) {
        Object.keys(defaults).forEach(function(key) {
            Panner.defaults[key] = defaults[key];
        });
    };

    return node;
}

Panner.defaults = {
    panningModel: 'HRTF',
    distanceModel: 'linear',
    refDistance: 1,
    maxDistance: 1000,
    rolloffFactor: 1,
    coneInnerAngle: 360,
    coneOuterAngle: 0,
    coneOuterGain: 0
};

module.exports = Panner;
<|endoftext|>


<commit_before>(function(){
  var dc       = window.dc;
  var $        = dc.$;
  var _        = dc._;
  var Backbone = dc.Backbone;

  var definition = dc.embed.definition;
  var data = dc.embed.data;
  var views = dc.embed.views;
  definition.PageView = definition.PageView || Backbone.View.extend({
    events: {
      'click .DC-page-image': function(){ if (this.openNote){ this.openNote.close(); }}
    },

    initialize: function(options) {
      this.options = options;
      this.noteViews = {};

      this.listenTo(this.model, 'sync', this.render);
      this.renderOverlay = _.bind(this.renderOverlay,this);
    },

    prepare: function() {
      var notes = this.model.notes.forPage(this.options.page);
      _.each(notes, function(note){
        var noteView = new definition.NoteView({model: note});
        this.noteViews[note.id] = noteView;
        this.listenTo(noteView, 'opened', this.updateOpenNote);
        this.listenTo(noteView, 'closed', this.closeOpenNote);
      }, this);
      this.prepared = true;
    },

    render: function() {
      if (!this.prepared){ this.prepare(); }
      this.$el.html(JST['page']({model: this.model, pageNumber: this.options.page }));
      this.cacheDomReferences();
      if (this.dimensions) {
        this.renderNotes();
      } else {
        // Not sold on Promises given that they swallow error messages
        // unless you add an explicit path to catch possible errors.
        this.cacheNaturalDimensions().then(this.renderOverlay).then(
          undefined, function(error){ console.log(error);
        });
      }
    },

    renderOverlay: function() {
      var scale  = this.currentScale();
      var notes  = this.model.notes.forPage(this.options.page);
      //markup   = JST['debug']({
      //  scale: scale,
      //  height: this.dimensions.height,
      //  width: this.dimensions.width
      //}) + markup;
      this.$overlay.empty();
      var noteViews = _.map(notes, function(note){ return this.noteViews[note.id].render(scale) }, this);
      this.$overlay.append(_.map(noteViews, function(v){return v.$el}));
    },

    resize: function() {
      var scale = this.currentScale();
      this.$el.css({
        width: this.width * scale,
        height: this.height * scale
      })
      _.each(this.noteViews, function(view){ view.resize(scale); });
    },

    cacheDomReferences: function() {
      this.$image = this.$('.DC-page-image');
      this.$overlay = this.$('.DC-note-overlay');
    },

    cacheNaturalDimensions: function() {
      var view = this;
      return new Promise(function(resolve, reject){
        var unstyledImage = $(new Image());
        unstyledImage.load(function(){
          view.dimensions = {
            height: this.height,
            width: this.width,
            aspectRatio: this.height / this.width
          };
          resolve();
        });
        unstyledImage.attr('src', view.model.imageUrl(view.options.page));
      });
    },

    currentScale: function() { return this.$image.width() / this.dimensions.width; },

    updateOpenNote: function(justOpened){
      if (this.openNote && this.openNote != justOpened) { this.openNote.close(); }
      this.openNote = justOpened;
    },
    closeOpenNote: function(){ this.openNote = undefined; }
  });
})();
<commit_msg>semicolons amirite.<commit_after>(function(){
  var dc       = window.dc;
  var $        = dc.$;
  var _        = dc._;
  var Backbone = dc.Backbone;

  var definition = dc.embed.definition;
  var data = dc.embed.data;
  var views = dc.embed.views;
  definition.PageView = definition.PageView || Backbone.View.extend({
    events: {
      'click .DC-page-image': function(){ if (this.openNote){ this.openNote.close(); }}
    },

    initialize: function(options) {
      this.options = options;
      this.noteViews = {};

      this.listenTo(this.model, 'sync', this.render);
      this.renderOverlay = _.bind(this.renderOverlay,this);
    },

    prepare: function() {
      var notes = this.model.notes.forPage(this.options.page);
      _.each(notes, function(note){
        var noteView = new definition.NoteView({model: note});
        this.noteViews[note.id] = noteView;
        this.listenTo(noteView, 'opened', this.updateOpenNote);
        this.listenTo(noteView, 'closed', this.closeOpenNote);
      }, this);
      this.prepared = true;
    },

    render: function() {
      if (!this.prepared){ this.prepare(); }
      this.$el.html(JST['page']({model: this.model, pageNumber: this.options.page }));
      this.cacheDomReferences();
      if (this.dimensions) {
        this.renderOverlay();
      } else {
        // Not sold on Promises given that they swallow error messages
        // unless you add an explicit path to catch possible errors.
        this.cacheNaturalDimensions().then(this.renderOverlay).then(
          undefined, function(error){ console.log(error);
        });
      }
    },

    renderOverlay: function() {
      var scale  = this.currentScale();
      var notes  = this.model.notes.forPage(this.options.page);
      //markup   = JST['debug']({
      //  scale: scale,
      //  height: this.dimensions.height,
      //  width: this.dimensions.width
      //}) + markup;
      this.$overlay.empty();
      var noteViews = _.map(notes, function(note){ return this.noteViews[note.id].render(scale); }, this);
      this.$overlay.append(_.map(noteViews, function(v){return v.$el;}));
    },

    resize: function() {
      var scale = this.currentScale();
      this.$el.css({
        width: this.width * scale,
        height: this.height * scale
      });
      _.each(this.noteViews, function(view){ view.resize(scale); });
    },

    cacheDomReferences: function() {
      this.$image = this.$('.DC-page-image');
      this.$overlay = this.$('.DC-note-overlay');
    },

    cacheNaturalDimensions: function() {
      var view = this;
      return new Promise(function(resolve, reject){
        var unstyledImage = $(new Image());
        unstyledImage.load(function(){
          view.dimensions = {
            height: this.height,
            width: this.width,
            aspectRatio: this.height / this.width
          };
          resolve();
        });
        unstyledImage.attr('src', view.model.imageUrl(view.options.page));
      });
    },

    currentScale: function() { return this.$image.width() / this.dimensions.width; },

    updateOpenNote: function(justOpened){
      if (this.openNote && this.openNote != justOpened) { this.openNote.close(); }
      this.openNote = justOpened;
    },
    closeOpenNote: function(){ this.openNote = undefined; }
  });
})();
<|endoftext|>


<commit_before>/**
 * MIME types and extensions
 */
const MIME = {

    // application
    '7z': 'application/x-7z-compressed',
    'arc': 'application/octet-stream',
    'ai': 'application/postscript',
    'bin': 'application/octet-stream',
    'bz': 'application/x-bzip',
    'bz2': 'application/x-bzip2',
    'eps': 'application/postscript',
    'exe': 'application/octet-stream',
    'gz': 'application/x-gzip',
    'gzip': 'application/x-gzip',
    'js': 'application/javascript',
    'json': 'application/json',
    'ogg': 'application/ogg',
    'pdf': 'application/pdf',
    'ps': 'application/postscript',
    'psd': 'application/octet-stream',
    'rar': 'application/x-rar-compressed',
    'rev': 'application/x-rar-compressed',
    'swf': 'application/x-shockwave-flash',
    'tar': 'application/x-tar',
    'xhtml': 'application/xhtml+xml',
    'xml': 'application/xml',
    'zip': 'application/zip',

    // audio
    'aif': 'audio/aiff',
    'aifc': 'audio/aiff',
    'aiff': 'audio/aiff',
    'au': 'audio/basic',
    'midi': 'audio/midi',
    'mp2': 'audio/mpeg',
    'mp3': 'audio/mpeg',
    'mpa': 'audio/mpeg',
    'ra': 'audio/vnd.rn-realaudio',
    'wav': 'audio/x-wav',
    'weba': 'audio/webm',
    'wma': 'audio/x-ms-wma',

    // image
    'avs': 'image/avs-video',
    'bmp': 'image/x-windows-bmp',
    'gif': 'image/gif',
    'ico': 'image/vnd.microsoft.icon',
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpg',
    'mjpg': 'image/x-motion-jpeg',
    'pic': 'image/pic',
    'png': 'image/png',
    'svg': 'image/svg+xml',
    'tif': 'image/tiff',
    'tiff': 'image/tiff',

    // text
    'css': 'text/css',
    'csv': 'text/csv',
    'html': 'text/html',
    'txt': 'text/plain',

    // video
    'avi': 'video/avi',
    'dv': 'video/x-dv',
    'flv': 'video/x-flv',
    'mov': 'video/quicktime',
    'mp4': 'video/mp4',
    'mpeg': 'video/mpeg',
    'mpg': 'video/mpg',
    'vdo': 'video/vdo',
    'webm': 'video/webm',
    'wmv': 'video/x-ms-wmv',

    // specific to vendors
    'doc': 'application/msword',
    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'odb': 'application/vnd.oasis.opendocument.database',
    'odc': 'application/vnd.oasis.opendocument.chart',
    'odf': 'application/vnd.oasis.opendocument.formula',
    'odg': 'application/vnd.oasis.opendocument.graphics',
    'odi': 'application/vnd.oasis.opendocument.image',
    'odm': 'application/vnd.oasis.opendocument.text-master',
    'odp': 'application/vnd.oasis.opendocument.presentation',
    'ods': 'application/vnd.oasis.opendocument.spreadsheet',
    'odt': 'application/vnd.oasis.opendocument.text',
    'otg': 'application/vnd.oasis.opendocument.graphics-template',
    'otp': 'application/vnd.oasis.opendocument.presentation-template',
    'ots': 'application/vnd.oasis.opendocument.spreadsheet-template',
    'ott': 'application/vnd.oasis.opendocument.text-template',
    'ppt': 'application/vnd.ms-powerpoint',
    'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'xls': 'application/vnd.ms-excel',
    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

};

/**
 * Adds the MIME type for an extension
 * @param extension
 * @param mime
 */
UploadFS.addMimeType = function (extension, mime) {
    MIME[extension.toLowerCase()] = mime;
};

/**
 * Returns the MIME type of the extension
 * @param extension
 * @returns {*}
 */
UploadFS.getMimeType = function (extension) {
    if (extension) {
        extension = extension.toLowerCase();
        return MIME[extension];
    }
};

/**
 * Returns all MIME types
 */
UploadFS.getMimeTypes = function () {
    return MIME;
};
<commit_msg>Adds OGG file types<commit_after>/**
 * MIME types and extensions
 */
const MIME = {

    // application
    '7z': 'application/x-7z-compressed',
    'arc': 'application/octet-stream',
    'ai': 'application/postscript',
    'bin': 'application/octet-stream',
    'bz': 'application/x-bzip',
    'bz2': 'application/x-bzip2',
    'eps': 'application/postscript',
    'exe': 'application/octet-stream',
    'gz': 'application/x-gzip',
    'gzip': 'application/x-gzip',
    'js': 'application/javascript',
    'json': 'application/json',
    'ogx': 'application/ogg',
    'pdf': 'application/pdf',
    'ps': 'application/postscript',
    'psd': 'application/octet-stream',
    'rar': 'application/x-rar-compressed',
    'rev': 'application/x-rar-compressed',
    'swf': 'application/x-shockwave-flash',
    'tar': 'application/x-tar',
    'xhtml': 'application/xhtml+xml',
    'xml': 'application/xml',
    'zip': 'application/zip',

    // audio
    'aif': 'audio/aiff',
    'aifc': 'audio/aiff',
    'aiff': 'audio/aiff',
    'au': 'audio/basic',
    'flac': 'audio/flac',
    'midi': 'audio/midi',
    'mp2': 'audio/mpeg',
    'mp3': 'audio/mpeg',
    'mpa': 'audio/mpeg',
    'oga': 'audio/ogg',
    'ogg': 'audio/ogg',
    'opus': 'audio/ogg',
    'ra': 'audio/vnd.rn-realaudio',
    'spx': 'audio/ogg',
    'wav': 'audio/x-wav',
    'weba': 'audio/webm',
    'wma': 'audio/x-ms-wma',

    // image
    'avs': 'image/avs-video',
    'bmp': 'image/x-windows-bmp',
    'gif': 'image/gif',
    'ico': 'image/vnd.microsoft.icon',
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpg',
    'mjpg': 'image/x-motion-jpeg',
    'pic': 'image/pic',
    'png': 'image/png',
    'svg': 'image/svg+xml',
    'tif': 'image/tiff',
    'tiff': 'image/tiff',

    // text
    'css': 'text/css',
    'csv': 'text/csv',
    'html': 'text/html',
    'txt': 'text/plain',

    // video
    'avi': 'video/avi',
    'dv': 'video/x-dv',
    'flv': 'video/x-flv',
    'mov': 'video/quicktime',
    'mp4': 'video/mp4',
    'mpeg': 'video/mpeg',
    'mpg': 'video/mpg',
    'ogv': 'video/ogg',
    'vdo': 'video/vdo',
    'webm': 'video/webm',
    'wmv': 'video/x-ms-wmv',

    // specific to vendors
    'doc': 'application/msword',
    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'odb': 'application/vnd.oasis.opendocument.database',
    'odc': 'application/vnd.oasis.opendocument.chart',
    'odf': 'application/vnd.oasis.opendocument.formula',
    'odg': 'application/vnd.oasis.opendocument.graphics',
    'odi': 'application/vnd.oasis.opendocument.image',
    'odm': 'application/vnd.oasis.opendocument.text-master',
    'odp': 'application/vnd.oasis.opendocument.presentation',
    'ods': 'application/vnd.oasis.opendocument.spreadsheet',
    'odt': 'application/vnd.oasis.opendocument.text',
    'otg': 'application/vnd.oasis.opendocument.graphics-template',
    'otp': 'application/vnd.oasis.opendocument.presentation-template',
    'ots': 'application/vnd.oasis.opendocument.spreadsheet-template',
    'ott': 'application/vnd.oasis.opendocument.text-template',
    'ppt': 'application/vnd.ms-powerpoint',
    'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'xls': 'application/vnd.ms-excel',
    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

};

/**
 * Adds the MIME type for an extension
 * @param extension
 * @param mime
 */
UploadFS.addMimeType = function (extension, mime) {
    MIME[extension.toLowerCase()] = mime;
};

/**
 * Returns the MIME type of the extension
 * @param extension
 * @returns {*}
 */
UploadFS.getMimeType = function (extension) {
    if (extension) {
        extension = extension.toLowerCase();
        return MIME[extension];
    }
};

/**
 * Returns all MIME types
 */
UploadFS.getMimeTypes = function () {
    return MIME;
};
<|endoftext|>


<commit_before>/* eslint-disable
    consistent-return,
    func-names,
    global-require,
    import/no-dynamic-require,
    import/no-unresolved,
    no-param-reassign,
    no-restricted-syntax,
    no-shadow,
    no-underscore-dangle,
    no-use-before-define,
    no-var,
    prefer-destructuring,
    vars-on-top,
*/
const path = require('path');
const fs = require('fs');
const manifest = require('fbp-manifest');
const fbpGraph = require('fbp-graph');

// We allow components to be un-compiled CoffeeScript
const CoffeeScript = require('coffeescript');
const utils = require('../Utils');

if (typeof CoffeeScript.register !== 'undefined') {
  CoffeeScript.register();
}

var registerCustomLoaders = function (loader, componentLoaders, callback) {
  if (!componentLoaders.length) {
    callback(null);
    return;
  }
  const customLoader = require(componentLoaders.shift());
  loader.registerLoader(customLoader, (err) => {
    if (err) {
      callback(err);
      return;
    }
    registerCustomLoaders(loader, componentLoaders, callback);
  });
};

const registerModules = function (loader, modules, callback) {
  const compatible = modules.filter((m) => ['noflo', 'noflo-nodejs'].includes(m.runtime));
  const componentLoaders = [];
  for (const m of compatible) {
    if (m.icon) { loader.setLibraryIcon(m.name, m.icon); }

    if (m.noflo != null ? m.noflo.loader : undefined) {
      const loaderPath = path.resolve(loader.baseDir, m.base, m.noflo.loader);
      componentLoaders.push(loaderPath);
    }

    for (const c of m.components) {
      loader.registerComponent(m.name, c.name, path.resolve(loader.baseDir, c.path));
    }
  }

  registerCustomLoaders(loader, componentLoaders, callback);
};

const manifestLoader = {
  writeCache(loader, options, manifest, callback) {
    const filePath = path.resolve(loader.baseDir, options.manifest);
    fs.writeFile(filePath, JSON.stringify(manifest, null, 2),
      { encoding: 'utf-8' },
      callback);
  },

  readCache(loader, options, callback) {
    options.discover = false;
    manifest.load.load(loader.baseDir, options, callback);
  },

  prepareManifestOptions(loader) {
    if (!loader.options) { loader.options = {}; }
    const options = {};
    options.runtimes = loader.options.runtimes || [];
    if (options.runtimes.indexOf('noflo') === -1) { options.runtimes.push('noflo'); }
    options.recursive = typeof loader.options.recursive === 'undefined' ? true : loader.options.recursive;
    options.manifest = loader.options.manifest || 'fbp.json';
    return options;
  },

  listComponents(loader, manifestOptions, callback) {
    this.readCache(loader, manifestOptions, (err, manifest) => {
      if (err) {
        if (!loader.options.discover) {
          callback(err);
          return;
        }
        dynamicLoader.listComponents(loader, manifestOptions, (err, modules) => {
          if (err) {
            callback(err);
            return;
          }
          return this.writeCache(loader, manifestOptions, {
            version: 1,
            modules,
          },
          (err) => {
            if (err) {
              callback(err);
              return;
            }
            callback(null, modules);
          });
        });
        return;
      }
      registerModules(loader, manifest.modules, (err) => {
        if (err) {
          callback(err);
          return;
        }
        callback(null, manifest.modules);
      });
    });
  },
};

var dynamicLoader = {
  listComponents(loader, manifestOptions, callback) {
    manifestOptions.discover = true;
    manifest.list.list(loader.baseDir, manifestOptions, (err, modules) => {
      if (err) {
        callback(err);
        return;
      }
      registerModules(loader, modules, (err) => {
        if (err) {
          callback(err);
          return;
        }
        callback(null, modules);
      });
    });
  },
};

const registerSubgraph = function (loader) {
  // Inject subgraph component
  let graphPath;
  if (path.extname(__filename) === '.js') {
    graphPath = path.resolve(__dirname, '../../components/Graph.js');
  } else {
    graphPath = path.resolve(__dirname, '../../components/Graph.coffee');
  }
  loader.registerComponent(null, 'Graph', graphPath);
};

exports.register = function (loader, callback) {
  const manifestOptions = manifestLoader.prepareManifestOptions(loader);

  if (loader.options != null ? loader.options.cache : undefined) {
    manifestLoader.listComponents(loader, manifestOptions, (err, modules) => {
      if (err) {
        callback(err);
        return;
      }
      registerSubgraph(loader);
      callback(null, modules);
    });
    return;
  }

  dynamicLoader.listComponents(loader, manifestOptions, (err, modules) => {
    if (err) {
      callback(err);
      return;
    }
    registerSubgraph(loader);
    callback(null, modules);
  });
};

exports.dynamicLoad = function (name, cPath, metadata, callback) {
  let e; let implementation; let
    instance;
  try {
    implementation = require(cPath);
  } catch (error) {
    e = error;
    callback(e);
    return;
  }

  if (typeof implementation.getComponent === 'function') {
    try {
      instance = implementation.getComponent(metadata);
    } catch (error1) {
      e = error1;
      callback(e);
      return;
    }
  } else if (typeof implementation === 'function') {
    try {
      instance = implementation(metadata);
    } catch (error2) {
      e = error2;
      callback(e);
      return;
    }
  } else {
    callback(new Error(`Unable to instantiate ${cPath}`));
    return;
  }
  if (typeof name === 'string') { instance.componentName = name; }
  callback(null, instance);
};

exports.setSource = function (loader, packageId, name, source, language, callback) {
  let e; let
    implementation;
  const Module = require('module');
  if (language === 'coffeescript') {
    try {
      source = CoffeeScript.compile(source,
        { bare: true });
    } catch (error) {
      e = error;
      callback(e);
      return;
    }
  }
  try {
    // Use the Node.js module API to evaluate in the correct directory context
    const modulePath = path.resolve(loader.baseDir, `./components/${name}.js`);
    const moduleImpl = new Module(modulePath, module);
    moduleImpl.paths = Module._nodeModulePaths(path.dirname(modulePath));
    moduleImpl.filename = modulePath;
    moduleImpl._compile(source, modulePath);
    implementation = moduleImpl.exports;
  } catch (error1) {
    e = error1;
    callback(e);
    return;
  }
  if ((typeof implementation !== 'function') && (typeof implementation.getComponent !== 'function')) {
    callback(new Error('Provided source failed to create a runnable component'));
    return;
  }

  loader.registerComponent(packageId, name, implementation, callback);
};

exports.getSource = function (loader, name, callback) {
  let component = loader.components[name];
  if (!component) {
    // Try an alias
    for (const componentName in loader.components) {
      if (componentName.split('/')[1] === name) {
        component = loader.components[componentName];
        name = componentName;
        break;
      }
    }
    if (!component) {
      callback(new Error(`Component ${name} not installed`));
      return;
    }
  }

  const nameParts = name.split('/');
  if (nameParts.length === 1) {
    nameParts[1] = nameParts[0];
    nameParts[0] = '';
  }

  if (loader.isGraph(component)) {
    if (typeof component === 'object') {
      if (typeof component.toJSON === 'function') {
        callback(null, {
          name: nameParts[1],
          library: nameParts[0],
          code: JSON.stringify(component.toJSON()),
          language: 'json',
        });
        return;
      }
      callback(new Error(`Can't provide source for ${name}. Not a file`));
      return;
    }
    fbpGraph.graph.loadFile(component, (err, graph) => {
      if (err) {
        callback(err);
        return;
      }
      if (!graph) { return callback(new Error('Unable to load graph')); }
      return callback(null, {
        name: nameParts[1],
        library: nameParts[0],
        code: JSON.stringify(graph.toJSON()),
        language: 'json',
      });
    });
    return;
  }

  if (typeof component !== 'string') {
    callback(new Error(`Can't provide source for ${name}. Not a file`));
    return;
  }

  fs.readFile(component, 'utf-8', (err, code) => {
    if (err) {
      callback(err);
      return;
    }
    callback(null, {
      name: nameParts[1],
      library: nameParts[0],
      language: utils.guessLanguageFromFilename(component),
      code,
    });
  });
};
<commit_msg>Update NodeJs after decaffeination<commit_after>/* eslint-disable
    global-require,
    import/no-dynamic-require,
    import/no-unresolved,
    no-underscore-dangle,
    prefer-destructuring,
*/
const path = require('path');
const fs = require('fs');
const manifest = require('fbp-manifest');
const fbpGraph = require('fbp-graph');

// We allow components to be un-compiled CoffeeScript
const CoffeeScript = require('coffeescript');
const utils = require('../Utils');

if (typeof CoffeeScript.register !== 'undefined') {
  CoffeeScript.register();
}

function registerCustomLoaders(loader, componentLoaders, callback) {
  if (!componentLoaders.length) {
    callback(null);
    return;
  }
  const customLoader = require(componentLoaders.shift());
  loader.registerLoader(customLoader, (err) => {
    if (err) {
      callback(err);
      return;
    }
    registerCustomLoaders(loader, componentLoaders, callback);
  });
}

function registerModules(loader, modules, callback) {
  const compatible = modules.filter((m) => ['noflo', 'noflo-nodejs'].includes(m.runtime));
  const componentLoaders = [];
  compatible.forEach((m) => {
    if (m.icon) { loader.setLibraryIcon(m.name, m.icon); }

    if (m.noflo != null ? m.noflo.loader : undefined) {
      const loaderPath = path.resolve(loader.baseDir, m.base, m.noflo.loader);
      componentLoaders.push(loaderPath);
    }

    m.components.forEach((c) => {
      loader.registerComponent(m.name, c.name, path.resolve(loader.baseDir, c.path));
    });
  });

  registerCustomLoaders(loader, componentLoaders, callback);
}

const dynamicLoader = {
  listComponents(loader, manifestOptions, callback) {
    const opts = manifestOptions;
    opts.discover = true;
    manifest.list.list(loader.baseDir, opts, (err, modules) => {
      if (err) {
        callback(err);
        return;
      }
      registerModules(loader, modules, (err2) => {
        if (err2) {
          callback(err2);
          return;
        }
        callback(null, modules);
      });
    });
  },
};

const manifestLoader = {
  writeCache(loader, options, manifestContents, callback) {
    const filePath = path.resolve(loader.baseDir, options.manifest);
    fs.writeFile(filePath, JSON.stringify(manifestContents, null, 2),
      { encoding: 'utf-8' },
      callback);
  },

  readCache(loader, options, callback) {
    const opts = options;
    opts.discover = false;
    manifest.load.load(loader.baseDir, opts, callback);
  },

  prepareManifestOptions(loader) {
    const l = loader;
    if (!l.options) { l.options = {}; }
    const options = {};
    options.runtimes = l.options.runtimes || [];
    if (options.runtimes.indexOf('noflo') === -1) { options.runtimes.push('noflo'); }
    options.recursive = typeof l.options.recursive === 'undefined' ? true : l.options.recursive;
    options.manifest = l.options.manifest || 'fbp.json';
    return options;
  },

  listComponents(loader, manifestOptions, callback) {
    this.readCache(loader, manifestOptions, (err, manifestContents) => {
      if (err) {
        if (!loader.options.discover) {
          callback(err);
          return;
        }
        dynamicLoader.listComponents(loader, manifestOptions, (err2, modules) => {
          if (err2) {
            callback(err2);
            return;
          }
          this.writeCache(loader, manifestOptions, {
            version: 1,
            modules,
          },
          (err3) => {
            if (err3) {
              callback(err3);
              return;
            }
            callback(null, modules);
          });
        });
        return;
      }
      registerModules(loader, manifestContents.modules, (err2) => {
        if (err2) {
          callback(err2);
          return;
        }
        callback(null, manifestContents.modules);
      });
    });
  },
};

function registerSubgraph(loader) {
  // Inject subgraph component
  const graphPath = path.resolve(__dirname, '../../components/Graph.js');
  loader.registerComponent(null, 'Graph', graphPath);
}

exports.register = function register(loader, callback) {
  const manifestOptions = manifestLoader.prepareManifestOptions(loader);

  if (loader.options != null ? loader.options.cache : undefined) {
    manifestLoader.listComponents(loader, manifestOptions, (err, modules) => {
      if (err) {
        callback(err);
        return;
      }
      registerSubgraph(loader);
      callback(null, modules);
    });
    return;
  }

  dynamicLoader.listComponents(loader, manifestOptions, (err, modules) => {
    if (err) {
      callback(err);
      return;
    }
    registerSubgraph(loader);
    callback(null, modules);
  });
};

exports.dynamicLoad = function dynamicLoad(name, cPath, metadata, callback) {
  let e; let implementation; let
    instance;
  try {
    implementation = require(cPath);
  } catch (error) {
    e = error;
    callback(e);
    return;
  }

  if (typeof implementation.getComponent === 'function') {
    try {
      instance = implementation.getComponent(metadata);
    } catch (error1) {
      e = error1;
      callback(e);
      return;
    }
  } else if (typeof implementation === 'function') {
    try {
      instance = implementation(metadata);
    } catch (error2) {
      e = error2;
      callback(e);
      return;
    }
  } else {
    callback(new Error(`Unable to instantiate ${cPath}`));
    return;
  }
  if (typeof name === 'string') { instance.componentName = name; }
  callback(null, instance);
};

exports.setSource = function setSource(loader, packageId, name, source, language, callback) {
  let e; let implementation;
  const Module = require('module');
  let src = source;
  if (language === 'coffeescript') {
    try {
      src = CoffeeScript.compile(src,
        { bare: true });
    } catch (error) {
      e = error;
      callback(e);
      return;
    }
  }
  try {
    // Use the Node.js module API to evaluate in the correct directory context
    const modulePath = path.resolve(loader.baseDir, `./components/${name}.js`);
    const moduleImpl = new Module(modulePath, module);
    moduleImpl.paths = Module._nodeModulePaths(path.dirname(modulePath));
    moduleImpl.filename = modulePath;
    moduleImpl._compile(src, modulePath);
    implementation = moduleImpl.exports;
  } catch (error1) {
    e = error1;
    callback(e);
    return;
  }
  if ((typeof implementation !== 'function') && (typeof implementation.getComponent !== 'function')) {
    callback(new Error('Provided source failed to create a runnable component'));
    return;
  }

  loader.registerComponent(packageId, name, implementation, callback);
};

exports.getSource = function getSource(loader, name, callback) {
  let componentName = name;
  let component = loader.components[name];
  if (!component) {
    // Try an alias
    const keys = Object.keys(loader.components);
    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      if (key.split('/')[1] === name) {
        component = loader.components[key];
        componentName = key;
        break;
      }
    }
    if (!component) {
      callback(new Error(`Component ${componentName} not installed`));
      return;
    }
  }

  const nameParts = componentName.split('/');
  if (nameParts.length === 1) {
    nameParts[1] = nameParts[0];
    nameParts[0] = '';
  }

  if (loader.isGraph(component)) {
    if (typeof component === 'object') {
      if (typeof component.toJSON === 'function') {
        callback(null, {
          name: nameParts[1],
          library: nameParts[0],
          code: JSON.stringify(component.toJSON()),
          language: 'json',
        });
        return;
      }
      callback(new Error(`Can't provide source for ${componentName}. Not a file`));
      return;
    }
    fbpGraph.graph.loadFile(component, (err, graph) => {
      if (err) {
        callback(err);
        return;
      }
      if (!graph) {
        callback(new Error('Unable to load graph'));
        return;
      }
      callback(null, {
        name: nameParts[1],
        library: nameParts[0],
        code: JSON.stringify(graph.toJSON()),
        language: 'json',
      });
    });
    return;
  }

  if (typeof component !== 'string') {
    callback(new Error(`Can't provide source for ${componentName}. Not a file`));
    return;
  }

  fs.readFile(component, 'utf-8', (err, code) => {
    if (err) {
      callback(err);
      return;
    }
    callback(null, {
      name: nameParts[1],
      library: nameParts[0],
      language: utils.guessLanguageFromFilename(component),
      code,
    });
  });
};
<|endoftext|>